cocos create 3.X 控制角色左右上下移动
代码:
/** * 角色上下左右控制 * */ import { _decorator, Component, Node, Vec3, Input, EventKeyboard, KeyCode } from 'cc'; const { ccclass, property } = _decorator; @ccclass('Player') export class Player extends Component { xy: number = 5; up:boolean = false; down:boolean = false; left:boolean = false; right:boolean = false; pos:Vec3; start() { this.pos = this.node.getPosition(); console.log("start this.pos" + this.pos) let input:Input = new Input(); input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this); input.on(Input.EventType.KEY_UP, this.onKeyUp, this); } update(deltaTime: number) { this.move() } move(){ if(this.up){ this.pos.y += this.xy; } if(this.down){ this.pos.y -= this.xy; } if(this.left){ this.pos.x -= this.xy; } if(this.right){ this.pos.x += this.xy; } // 触及边界,停止移动 // 增加判断 this.node.setPosition(this.pos); } onKeyDown(event: EventKeyboard){ console.log("onKeyDown event " + event.keyCode) console.log("onKeyDown event " + event.keyCode ) switch (event.keyCode) { case KeyCode.KEY_W: case KeyCode.ARROW_UP: this.up = true; break; case KeyCode.KEY_S: case KeyCode.ARROW_DOWN: this.down = true; break; case KeyCode.KEY_A: case KeyCode.ARROW_LEFT: this.left = true; break; case KeyCode.KEY_D: case KeyCode.ARROW_RIGHT: this.right = true; break; } } onKeyUp(event: EventKeyboard){ console.log("onKeyUp event " + event.keyCode) switch (event.keyCode) { case KeyCode.KEY_W: case KeyCode.ARROW_UP: this.up = false; break; case KeyCode.KEY_S: case KeyCode.ARROW_DOWN: this.down = false; break; case KeyCode.KEY_A: case KeyCode.ARROW_LEFT: this.left = false; break; case KeyCode.KEY_D: case KeyCode.ARROW_RIGHT: this.right = false; break; } } }