Created
December 6, 2023 19:49
-
-
Save ealbinu/d62ee0b928feabda85ffd0940490eb7a to your computer and use it in GitHub Desktop.
Cocos Creator - Movimiento libre de 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(); | |
private _keys: { [keyCode: number]: boolean } = {}; | |
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) { | |
this._keys[event.keyCode] = true; | |
} | |
onKeyUp(event: EventKeyboard) { | |
this._keys[event.keyCode] = false; | |
} | |
update(deltaTime: number) { | |
this._direction.x = 0; | |
this._direction.y = 0; | |
// Update the direction based on the current state of the keys | |
if (this._keys[KeyCode.ARROW_LEFT] || this._keys[KeyCode.KEY_A]) { | |
this._direction.x = -1; | |
} else if (this._keys[KeyCode.ARROW_RIGHT] || this._keys[KeyCode.KEY_D]) { | |
this._direction.x = 1; | |
} | |
if (this._keys[KeyCode.ARROW_UP] || this._keys[KeyCode.KEY_W]) { | |
this._direction.y = 1; | |
} else if (this._keys[KeyCode.ARROW_DOWN] || this._keys[KeyCode.KEY_S]) { | |
this._direction.y = -1; | |
} | |
// Normalize the direction to allow for consistent movement speed in all directions | |
if (this._direction.lengthSqr() > 0) { | |
this._direction.normalize(); | |
} | |
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