yantar/assets/Scripts/FirstPersonController.ts
Georgy Shive a6a033ae55 добавил слушатель эмитера движения на класс перемещения персонажа
добавил эмитер в компонент содержащий кнопку
перемещения в стартовое положение
добавил ассет дома из фигмы
2025-03-14 03:09:15 +07:00

159 lines
6.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { _decorator, Component, Node, input, Input, EventKeyboard, EventMouse, KeyCode, Vec3, Quat, NodeSpace } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('FirstPersonController')
export class FirstPersonController extends Component {
@property({ type: Node })
public camera: Node | null = null;
@property
public moveSpeed: number = 5;
@property
public lookSpeed: number = 0.1;
@property
public speedStep: number = 1;
@property
public minSpeed: number = 1;
@property
public maxSpeed: number = 20;
// Вектор направления движения
private _moveDirection: Vec3 = new Vec3();
// Храним текущие углы поворота (в градусах)
private _eulerAngles: Vec3 = new Vec3();
// Флаг нажатия левой кнопки мыши
private _isLeftMousePressed: boolean = false;
// Для эмитации события движения – запоминаем последнее положение
private _lastEmittedPosition: Vec3 = new Vec3();
onLoad() {
input.on(Input.EventType.KEY_DOWN, this._onKeyDown, this);
input.on(Input.EventType.KEY_UP, this._onKeyUp, this);
input.on(Input.EventType.MOUSE_DOWN, this._onMouseDown, this);
input.on(Input.EventType.MOUSE_UP, this._onMouseUp, this);
input.on(Input.EventType.MOUSE_MOVE, this._onMouseMove, this);
input.on(Input.EventType.MOUSE_WHEEL, this._onMouseWheel, this);
// Инициализируем углы текущей ориентацией ноды player
this._eulerAngles = this.node.eulerAngles.clone();
// Сохраняем начальное положение для эмитации события "moved"
this._lastEmittedPosition = this.node.getPosition().clone();
}
onDestroy() {
input.off(Input.EventType.KEY_DOWN, this._onKeyDown, this);
input.off(Input.EventType.KEY_UP, this._onKeyUp, this);
input.off(Input.EventType.MOUSE_DOWN, this._onMouseDown, this);
input.off(Input.EventType.MOUSE_UP, this._onMouseUp, this);
input.off(Input.EventType.MOUSE_MOVE, this._onMouseMove, this);
input.off(Input.EventType.MOUSE_WHEEL, this._onMouseWheel, this);
}
private _onKeyDown(event: EventKeyboard) {
switch (event.keyCode) {
case KeyCode.KEY_W:
this._moveDirection.z = 1;
break;
case KeyCode.KEY_S:
this._moveDirection.z = -1;
break;
case KeyCode.KEY_A:
this._moveDirection.x = -1;
break;
case KeyCode.KEY_D:
this._moveDirection.x = 1;
break;
case KeyCode.KEY_Q:
this._moveDirection.y = -1;
break;
case KeyCode.KEY_E:
this._moveDirection.y = 1;
break;
}
}
private _onKeyUp(event: EventKeyboard) {
switch (event.keyCode) {
case KeyCode.KEY_W:
case KeyCode.KEY_S:
this._moveDirection.z = 0;
break;
case KeyCode.KEY_A:
case KeyCode.KEY_D:
this._moveDirection.x = 0;
break;
case KeyCode.KEY_Q:
case KeyCode.KEY_E:
this._moveDirection.y = 0;
break;
}
}
private _onMouseDown(event: EventMouse) {
if (event.getButton() === 0) {
this._isLeftMousePressed = true;
}
}
private _onMouseUp(event: EventMouse) {
if (event.getButton() === 0) {
this._isLeftMousePressed = false;
}
}
private _onMouseMove(event: EventMouse) {
if (this._isLeftMousePressed) {
// Обновляем углы поворота: горизонтальный (yaw) и вертикальный (pitch)
this._eulerAngles.y -= event.movementX * this.lookSpeed;
this._eulerAngles.x -= event.movementY * this.lookSpeed;
// Ограничиваем pitch, чтобы не перевернуться
this._eulerAngles.x = Math.max(-89, Math.min(89, this._eulerAngles.x));
// Применяем поворот к ноде player
const newQuat = new Quat();
Quat.fromEuler(newQuat, this._eulerAngles.x, this._eulerAngles.y, 0);
this.node.setRotation(newQuat);
// Если камера дочерняя нода, сбрасываем её локальное вращение
if (this.camera) {
this.camera.setRotation(Quat.IDENTITY);
}
}
}
private _onMouseWheel(event: EventMouse) {
if (event.getScrollY() > 0) {
this.moveSpeed = Math.min(this.moveSpeed + this.speedStep, this.maxSpeed);
} else if (event.getScrollY() < 0) {
this.moveSpeed = Math.max(this.moveSpeed - this.speedStep, this.minSpeed);
}
console.log(`Current move speed: ${this.moveSpeed}`);
}
update(deltaTime: number) {
// Вычисляем направление движения с учётом ориентации игрока
const forward = Vec3.transformQuat(new Vec3(), Vec3.FORWARD, this.node.worldRotation);
const right = Vec3.transformQuat(new Vec3(), Vec3.RIGHT, this.node.worldRotation);
const move = new Vec3();
Vec3.scaleAndAdd(move, move, forward, this._moveDirection.z * this.moveSpeed * deltaTime);
Vec3.scaleAndAdd(move, move, right, this._moveDirection.x * this.moveSpeed * deltaTime);
Vec3.scaleAndAdd(move, move, Vec3.UP, this._moveDirection.y * this.moveSpeed * deltaTime);
// Перемещаем игрока в мировом пространстве
this.node.translate(move, NodeSpace.WORLD);
// После перемещения проверяем, изменилась ли позиция существенно, чтобы эмитировать событие "moved"
const currentPos = this.node.getPosition();
if (Vec3.distance(currentPos, this._lastEmittedPosition) > 0.1) {
this.node.emit('moved');
// Обновляем последнее сохранённое положение
this._lastEmittedPosition = currentPos.clone();
}
}
}