Files
esengine/extensions/cocos/cocos-ecs/assets/scripts/ecs/components/PlayerInputComponent.ts

124 lines
2.9 KiB
TypeScript
Raw Normal View History

2025-06-17 00:32:16 +08:00
import { Component } from '@esengine/ecs-framework';
import { Vec2 } from 'cc';
/**
* -
*
*
* 1.
* 2.
* 3. InputSystem中实现
*/
export class PlayerInputComponent extends Component {
/** 移动输入方向(-1到1 */
public moveDirection: Vec2 = new Vec2();
/** 按键状态 */
public keys: { [key: string]: boolean } = {};
/** 鼠标位置 */
public mousePosition: Vec2 = new Vec2();
/** 鼠标按键状态 */
public mouseButtons: { left: boolean; right: boolean; middle: boolean } = {
left: false,
right: false,
middle: false
};
/** 是否启用输入 */
public inputEnabled: boolean = true;
/** 输入敏感度 */
public sensitivity: number = 1.0;
constructor() {
super();
}
/**
*
*/
setMoveDirection(x: number, y: number) {
this.moveDirection.set(x, y);
// 标准化方向向量(对角线移动不应该更快)
if (this.moveDirection.lengthSqr() > 1) {
this.moveDirection.normalize();
}
}
/**
*
*/
setKey(key: string, pressed: boolean) {
this.keys[key] = pressed;
}
/**
*
*/
isKeyPressed(key: string): boolean {
return this.keys[key] || false;
}
/**
*
*/
hasMovementInput(): boolean {
return this.moveDirection.lengthSqr() > 0.01;
}
/**
*
*/
getNormalizedMoveDirection(): Vec2 {
const result = new Vec2(this.moveDirection);
if (result.lengthSqr() > 0) {
result.normalize();
}
return result;
}
/**
*
*/
setMousePosition(x: number, y: number) {
this.mousePosition.set(x, y);
}
/**
*
*/
setMouseButton(button: 'left' | 'right' | 'middle', pressed: boolean) {
this.mouseButtons[button] = pressed;
}
/**
*
*/
isMouseButtonPressed(button: 'left' | 'right' | 'middle'): boolean {
return this.mouseButtons[button];
}
/**
*
*/
clearInput() {
this.moveDirection.set(0, 0);
this.keys = {};
this.mouseButtons.left = false;
this.mouseButtons.right = false;
this.mouseButtons.middle = false;
}
/**
*
*/
disableInput() {
this.inputEnabled = false;
this.clearInput();
}
/**
*
*/
enableInput() {
this.inputEnabled = true;
}
}