import { _decorator, Component, EventKeyboard, input, Input, KeyCode, Vec2, Vec3 } from ‘cc’;
const { ccclass, property } = _decorator;
@ccclass(‘testMove’)
export class testMove extends Component {
private moveDir: Vec2 = new Vec2(0, 0);
private isRight: boolean;
onLoad() {
this.onLoadKey();
this.isRight = true;
}
onLoadKey() {
input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
}
onDestroy() {
input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
}
onKeyDown(event: EventKeyboard) {
switch (event.keyCode) {
case KeyCode.KEY_A:
case KeyCode.ARROW_LEFT:
this.moveDir.x = -1;
this.isRight = false;
break;
case KeyCode.KEY_D:
case KeyCode.ARROW_RIGHT:
this.moveDir.x = 1;
this.isRight = true;
break;
case KeyCode.KEY_S:
case KeyCode.ARROW_DOWN:
this.moveDir.y = -1;
break;
case KeyCode.KEY_W:
case KeyCode.ARROW_UP:
this.moveDir.y = 1;
break;
}
}
onKeyUp(event: EventKeyboard) {
switch (event.keyCode) {
case KeyCode.KEY_A:
case KeyCode.KEY_D:
case KeyCode.ARROW_LEFT:
case KeyCode.ARROW_RIGHT:
this.moveDir.x = 0;
break;
case KeyCode.KEY_S:
case KeyCode.KEY_W:
case KeyCode.ARROW_UP:
case KeyCode.ARROW_DOWN:
this.moveDir.y = 0;
break;
}
}
update(deltaTime: number) {
const move = new Vec3(this.moveDir.x, this.moveDir.y, 0).normalize().multiplyScalar(300 * deltaTime);
this.node.setPosition(this.node.position.clone().add(move));
}
}
somehow when i click the mouse, it triggered the key up event they are not related