// Learn TypeScript: // - https://docs.cocos.com/creator/manual/en/scripting/typescript.html // Learn Attribute: // - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html // Learn life-cycle callbacks: // - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html const {ccclass, property} = cc._decorator; @ccclass export default class NewClass extends cc.Component { //方向控制(一開始向右) direction = cc.v2(1,0); onLoad () { //兩種寫法都可以 cc.systemEvent.on("keydown", this.movedirec, this); //cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.movedirec, this); } movedirec(event:cc.Event.EventKeyboard) { //設定各種方向的向量 if(event.keyCode == cc.macro.KEY.right) this.direction = cc.v2(1,0); else if(event.keyCode == cc.macro.KEY.left) this.direction = cc.v2(-1,0); else if(event.keyCode == cc.macro.KEY.up) this.direction = cc.v2(0,1); else if(event.keyCode == cc.macro.KEY.down) this.direction = cc.v2(0,-1); else if(event.keyCode == cc.macro.KEY.space) this.direction = null; //原地不動,direction = null; } start () { } update (dt) { //1.先取得目前node的坐標=Pos var pos = this.node.getPosition(); //2.然後再加上方向向量(pos = pos + direction) //但是要(x,y)分開來加上 pos.x += this.direction.x; pos.y += this.direction.y; //3.設定節點node的最新位置 this.node.setPosition(pos); } }