Cocos Creator升级2.0以后发现原来写的一些代码开始报弃用警告了,今天有空学习下新API并更新下原来的代码,之前写的实现监听touch起动停事件的代码是这样写的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | // use this for initialization onLoad: function () { let self = this ; cc.eventManager.addListener({ event: cc.EventListener.TOUCH_ONE_BY_ONE, onTouchBegan: function (touch, event) { // x = touch.getLocation().x // y = touch.getLocation().y return true ; }, onTouchMoved: function (touch, event) { // x = touch.getLocation().x // y = touch.getLocation().y return true ; }, onTouchEnded: function (touch, event) { const x = touch.getLocation().x; const y = touch.getLocation().y; const cp = self.dragonPlayer.getPosition(); NetworkManager.instance.getNetPhoton().sendMyPost(cp.x, cp.y, x, y); const dist = cc.v2(x, y).sub(cp).mag(); self.dragonPlayer.stopAllActions(); self.dragonPlayer.runAction(cc.moveTo(dist / 80, x, y)); return true ; } }, self.node); }, |
在2.0里运行的时候就会被提示cc.eventManager已弃用,需要更新。于是阅读了下官方文档中的 v2.0 升级指南:https://docs.cocos.com/creator/manual/zh/release-notes/upgrade-guide-v2.0.html#34-%E4%BA%8B%E4%BB%B6%E7%B3%BB%E7%BB%9F%E5%8D%87%E7%BA%A7中的 事件系统升级 部分,发现新API的结构貌似是更好了一些,贴出更新后的实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // use this for initialization onLoad: function () { this .node.on( "touchstart" , () => { return true ; }, this ); this .node.on( "touchmove" , () => { return true ; }, this ); this .node.on( "touchend" , (event) => { const x = event.getLocation().x; const y = event.getLocation().y; const cp = this .dragonPlayer.getPosition(); NetworkManager.instance.getNetPhoton().sendMyPost(cp.x, cp.y, x, y); const dist = cc.v2(x, y).sub(cp).mag(); this .dragonPlayer.stopAllActions(); this .dragonPlayer.runAction(cc.moveTo(dist / 80, x, y)); return true ; }, this ); }, onDestroy: function () { this .node.off( "touchstart" ); this .node.off( "touchmove" ); this .node.off( "touchend" ); }, |
这样就实现了和原来一样的触摸事件处理逻辑,另外还有箭头方法省略了this闭包进回调函数的问题,onDestroy中的off不写也没关系,但看了文档学习了新的API后还是给加上了,至少能当个以后写自定义事件时的提示。
PS: 再额外多记录个cc.p的弃用问题,2.0中cc.p被cc.v2代替了,涉及到一些算两点间距离的API也有了一些变换,如下:
1 2 3 4 | // 旧版 //const dist = cc.pDistance(cp, cc.p(x, y)); // 新版 const dist = cc.v2(x, y).sub(cp).mag(); |
PPS: 这是Wordpress更新5.0后第一次用新的Gutenberg编辑器写的博文,一开始有点不适应,但写到直接设置SyntaxHighlighter代码段落的时候,发现有了UI直接设置代码语言等参数的体验简直比原来手输标签的体验好太多了!
博主友情提示:
如您在评论中需要提及如QQ号、电子邮件地址或其他隐私敏感信息,欢迎使用>>博主专用加密工具v3<<处理后发布,原文只有博主可以看到。
加载更多