这是一个使用cocos2d-html5的网页游戏。
我有一个游戏层,我想在里面处理鼠标悬停事件:
var GameLayer = cc.Layer.extend({
init:function () {
// ......
this.curPosition = null;
if( 'mouse' in sys.capabilities ) {
//this.setMouseEnabled(true);
this.mouseCaptured = false;
canvas = document.getElementById('gameCanvas');
canvas.addEventListener('mousemove', function(evt) {
var rect = document.getElementById('gameCanvas').getBoundingClientRect();
var curPos = new cc.Point();
curPos.x = evt.clientX - rect.left;
curPos.y = evt.clientY - rect.top;
// the problem is here, this is wrong since "this" stands for canvas here
this.curPosition = curPos
// also wrong
this.updatePosition(curPos);
}, false);
}
// ......
},
updatePosition:function (position) {
this.currentPosition = position;
// ......
}
});
var HelloWorldScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new GameLayer();
layer.init();
this.addChild(layer);
}
});我想要的只是调用函数或在侦听器中设置类变量。
希望有人能给点提示,谢谢:)
发布于 2013-08-06 21:30:29
您可以使用
init:function () {
var self=this;
//......然后,您可以使用以下命令调用侦听器中的类函数
canvas.addEventListener('mousemove', function(evt) {
self.updatePosition(1);
// .... 发布于 2014-01-28 10:10:46
Cocos2d-html5支持鼠标悬停事件。您需要在init函数中添加以下内容
if( 'mouse' in sys.capabilities ) {
this.setMouseEnabled(true);
}然后向您的层添加一个onMouseMoved委托函数。
onMouseMoved: function(event) {
var pos = event.getLocation();
console.log("onMouseMoved at: " + pos.x + " " + pos.y );
}要查看事件委托系统是如何工作的:http://cocos2d-x.org/npm/cctouch/index.html
https://stackoverflow.com/questions/18080504
复制相似问题