cocos2dx-js 学习之触摸相应机制
在学习了一段时间的 Cocos2d-x JS 之后,我收获颇丰。在网上偶然发现一篇关于 Cocos2d-x JS 中触摸响应机制的文章,觉得很不错,现在分享给大家。
触摸事件的添加
我们可以在构造函数中添加触摸事件,以下是具体的代码实现:
// 在事件管理器中添加监听
cc.eventManager.addListener({
// 规定事件监听为 ONE_BY_ONE
event: cc.EventListener.TOUCH_ONE_BY_ONE,
// 允许触摸传递
swallowTouches: true,
// 触摸开始回调函数
onTouchBegan: this.onTouchBegan,
// 触摸移动回调函数
onTouchMoved: this.onTouchMoved,
// 触摸结束回调函数
onTouchEnded: this.onTouchEnded
}, this);
上述代码通过 cc.eventManager.addListener 方法向事件管理器中添加了一个触摸事件监听器。其中:
event: cc.EventListener.TOUCH_ONE_BY_ONE:指定监听方式为逐个处理触摸事件,即一次只处理一个触摸点。swallowTouches: true:表示允许触摸事件传递,若设置为false,则触摸事件不会继续向下传递。onTouchBegan、onTouchMoved和onTouchEnded分别是触摸开始、触摸移动和触摸结束时触发的回调函数。
触摸事件的使用
下面是具体使用触摸事件的代码:
// 触摸开始回调函数
onTouchBegan: function(touch, event) {
var touches = touch.getLocation();
if (touches) {
cc.log("touches");
}
},
// 触摸移动回调函数
onTouchMoved: function(touch, event) {
cc.log("hello");
},
// 触摸结束回调函数
onTouchEnded: function(touch, event) {
cc.log("world");
}
代码解释
onTouchBegan函数:当触摸开始时触发。通过touch.getLocation()方法获取触摸点的位置,并将其赋值给touches变量。若touches不为空,则在控制台输出touches。onTouchMoved函数:当触摸点移动时触发,在控制台输出hello。onTouchEnded函数:当触摸结束时触发,在控制台输出world。
通过以上步骤,我们就可以在 Cocos2d-x JS 中实现基本的触摸响应机制。