squidGame/tgx-games-client/assets/level1/Script/PlayerController.ts

83 lines
2.4 KiB
TypeScript
Raw Normal View History

2025-02-17 21:36:37 +08:00
import { constant } from './framework/constant';
import { GameManager } from './gameManager';
import { _decorator, Component, Node, Vec2, Vec3, Quat, clamp, Touch, ColliderComponent, EventTouch, Camera, input, Input } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('PlayerController')
export class PlayerController extends Component {
protected _stateX: number = 0; // 1 positive, 0 static, -1 negative
protected _stateZ: number = 0;
protected _speed: number = 0.009;
ontouch :boolean = false;
private _oldX: number = 0;
@property(Camera)
public Camera: Camera = null!;
onLoad() {
// 监听触摸事件
input.on(Input.EventType.TOUCH_START, this.touchStart, this);
input.on(Input.EventType.TOUCH_MOVE, this.touchMove, this);
input.on(Input.EventType.TOUCH_END, this.touchEnd, this);
input.on(Input.EventType.TOUCH_CANCEL, this.touchCancel, this);
}
onDestroy()
{
input.off(Input.EventType.TOUCH_START);
input.off(Input.EventType.TOUCH_MOVE);
input.off(Input.EventType.TOUCH_END);
input.off(Input.EventType.TOUCH_CANCEL);
}
public touchStart(touch: EventTouch) {
this._stateX = 0;
this.ontouch = true;
}
public touchMove(touch: EventTouch) {
this._stateX = touch.getUIDelta().x;
//前后移动间距为3才视为移动避免太灵敏
if (Math.abs(this._stateX - this._oldX) <= 3) {
this._stateX = 0;
this._oldX = 0;
} else {
this._oldX = this._stateX;
}
}
public touchEnd(touch: EventTouch) {
this._stateX = 0;
this.ontouch = false;
}
public touchCancel(touch: EventTouch) {
this._stateX = 0;
this.ontouch = false;
}
private _updateCharacter(dt: number) {
this.node.position = new Vec3(this.node.position.x + this._stateX/6000 * dt, this.node.position.y, this.node.position.z - this._speed * dt);
this.Camera.node.position = new Vec3(this.Camera.node.position.x, this.Camera.node.position.y, this.Camera.node.position.z - this._speed * dt);
}
update(dtS: number) {
if(this.ontouch)
{
const dt = 1000 / constant.GAME_FRAME;
this._updateCharacter(dt);
}
}
2025-02-07 10:49:34 +08:00
}