Created
December 6, 2023 19:39
-
-
Save ealbinu/18588c147245b02810225864bb858344 to your computer and use it in GitHub Desktop.
CocosCreator - Mover objeto
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { _decorator, Component, input, Input, Vec3, EventKeyboard, KeyCode } from 'cc'; | |
const { ccclass, property } = _decorator; | |
@ccclass('PlayerController') | |
export class PlayerController extends Component { | |
@property | |
public moveSpeed: number = 100; | |
private _direction: Vec3 = new Vec3(); | |
onLoad() { | |
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.ARROW_LEFT: | |
case KeyCode.KEY_A: | |
this._direction.x = -1; | |
break; | |
case KeyCode.ARROW_RIGHT: | |
case KeyCode.KEY_D: | |
this._direction.x = 1; | |
break; | |
case KeyCode.ARROW_UP: | |
case KeyCode.KEY_W: | |
this._direction.y = 1; | |
break; | |
case KeyCode.ARROW_DOWN: | |
case KeyCode.KEY_S: | |
this._direction.y = -1; | |
break; | |
} | |
} | |
onKeyUp(event: EventKeyboard) { | |
switch(event.keyCode) { | |
case KeyCode.ARROW_LEFT: | |
case KeyCode.KEY_A: | |
case KeyCode.ARROW_RIGHT: | |
case KeyCode.KEY_D: | |
this._direction.x = 0; | |
break; | |
case KeyCode.ARROW_UP: | |
case KeyCode.KEY_W: | |
case KeyCode.ARROW_DOWN: | |
case KeyCode.KEY_S: | |
this._direction.y = 0; | |
break; | |
} | |
} | |
update(deltaTime: number) { | |
if (this._direction.length()) { | |
let deltaMove = new Vec3(this._direction.x * this.moveSpeed * deltaTime, | |
this._direction.y * this.moveSpeed * deltaTime, 0); | |
let newPosition = this.node.position.add(deltaMove); | |
this.node.setPosition(newPosition); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment