用js写一个cocos creator可以用的玩家按AD按钮移动方法
时间: 2023-12-29 11:02:02 浏览: 27
可以使用以下代码实现:
```javascript
cc.Class({
extends: cc.Component,
properties: {
speed: 100, // 移动速度
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
// 监听按键事件
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
},
start () {
},
update (dt) {
// 根据按键状态移动玩家
if (this.moveLeft) {
this.node.x -= this.speed * dt;
}
if (this.moveRight) {
this.node.x += this.speed * dt;
}
},
onKeyDown(event) {
switch(event.keyCode) {
case cc.KEY.a:
this.moveLeft = true;
break;
case cc.KEY.d:
this.moveRight = true;
break;
}
},
onKeyUp(event) {
switch(event.keyCode) {
case cc.KEY.a:
this.moveLeft = false;
break;
case cc.KEY.d:
this.moveRight = false;
break;
}
},
// 取消监听按键事件
onDestroy() {
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
},
});
```
这是一个基本的玩家移动脚本,监听键盘按键事件,根据按键状态移动玩家。具体使用方法可以参考Cocos Creator官方文档。