добавил слушатель эмитера движения на класс перемещения персонажа

добавил эмитер в компонент содержащий кнопку
перемещения в стартовое положение
добавил ассет дома из фигмы
This commit is contained in:
Georgy Shive 2025-03-14 03:09:15 +07:00
parent 1334dd95aa
commit a6a033ae55
14 changed files with 1149 additions and 495 deletions

9
assets/Icons.meta Normal file
View File

@ -0,0 +1,9 @@
{
"ver": "1.2.0",
"importer": "directory",
"imported": true,
"uuid": "f768e02a-5281-4724-8a00-cec2a7ba283f",
"files": [],
"subMetas": {},
"userData": {}
}

9
assets/Icons/Home.meta Normal file
View File

@ -0,0 +1,9 @@
{
"ver": "1.2.0",
"importer": "directory",
"imported": true,
"uuid": "a42e84ca-7587-4696-a1be-490a772e5c32",
"files": [],
"subMetas": {},
"userData": {}
}

View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
version="1.1"
id="svg2"
sodipodi:docname="home.svg"
inkscape:export-filename="home_pressed.png"
inkscape:export-xdpi="300"
inkscape:export-ydpi="300"
inkscape:version="1.4 (86a8ad7, 2024-10-11)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs2" />
<sodipodi:namedview
id="namedview2"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:zoom="38.708333"
inkscape:cx="2.467169"
inkscape:cy="12.116254"
inkscape:window-width="3840"
inkscape:window-height="2120"
inkscape:window-x="-12"
inkscape:window-y="-12"
inkscape:window-maximized="1"
inkscape:current-layer="svg2" />
<path
d="m 3,9 9,-7 9,7 v 11 c 0,0.5304 -0.2107,1.0391 -0.5858,1.4142 C 20.0391,21.7893 19.5304,22 19,22 H 5 C 4.46957,22 3.96086,21.7893 3.58579,21.4142 3.21071,21.0391 3,20.5304 3,20 Z"
stroke="#25282b"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
id="path1"
sodipodi:nodetypes="cccsssscsc"
style="fill:#ffffff;fill-opacity:1;stroke:#3574f8;stroke-opacity:1" />
<path
d="M9 22V12H15V22"
stroke="#25282B"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
id="path2"
style="fill:#ffffff;fill-opacity:1;stroke:#3574f8;stroke-opacity:1" />
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@ -0,0 +1,12 @@
{
"ver": "1.0.0",
"importer": "*",
"imported": true,
"uuid": "34368a77-231e-4b7e-81e0-4e6812239e21",
"files": [
".json",
".svg"
],
"subMetas": {},
"userData": {}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1,134 @@
{
"ver": "1.0.27",
"importer": "image",
"imported": true,
"uuid": "abe4c801-ca4a-4f3a-aafc-ca985258544d",
"files": [
".json",
".png"
],
"subMetas": {
"6c48a": {
"importer": "texture",
"uuid": "abe4c801-ca4a-4f3a-aafc-ca985258544d@6c48a",
"displayName": "home_hover",
"id": "6c48a",
"name": "texture",
"userData": {
"wrapModeS": "clamp-to-edge",
"wrapModeT": "clamp-to-edge",
"minfilter": "linear",
"magfilter": "linear",
"mipfilter": "none",
"anisotropy": 0,
"isUuid": true,
"imageUuidOrDatabaseUri": "abe4c801-ca4a-4f3a-aafc-ca985258544d",
"visible": false
},
"ver": "1.0.22",
"imported": true,
"files": [
".json"
],
"subMetas": {}
},
"f9941": {
"importer": "sprite-frame",
"uuid": "abe4c801-ca4a-4f3a-aafc-ca985258544d@f9941",
"displayName": "home_hover",
"id": "f9941",
"name": "spriteFrame",
"userData": {
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0,
"trimX": 6,
"trimY": 3,
"width": 63,
"height": 69,
"rawWidth": 75,
"rawHeight": 75,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"packable": true,
"pixelsToUnit": 100,
"pivotX": 0.5,
"pivotY": 0.5,
"meshType": 0,
"vertices": {
"rawPosition": [
-31.5,
-34.5,
0,
31.5,
-34.5,
0,
-31.5,
34.5,
0,
31.5,
34.5,
0
],
"indexes": [
0,
1,
2,
2,
1,
3
],
"uv": [
6,
72,
69,
72,
6,
3,
69,
3
],
"nuv": [
0.08,
0.04,
0.92,
0.04,
0.08,
0.96,
0.92,
0.96
],
"minPos": [
-31.5,
-34.5,
0
],
"maxPos": [
31.5,
34.5,
0
]
},
"isUuid": true,
"imageUuidOrDatabaseUri": "abe4c801-ca4a-4f3a-aafc-ca985258544d@6c48a",
"atlasUuid": ""
},
"ver": "1.0.12",
"imported": true,
"files": [
".json"
],
"subMetas": {}
}
},
"userData": {
"hasAlpha": true,
"type": "sprite-frame",
"fixAlphaTransparencyArtifacts": false,
"redirect": "abe4c801-ca4a-4f3a-aafc-ca985258544d@6c48a"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1,134 @@
{
"ver": "1.0.27",
"importer": "image",
"imported": true,
"uuid": "a69a42c0-5153-4727-a259-46e20a71889f",
"files": [
".json",
".png"
],
"subMetas": {
"6c48a": {
"importer": "texture",
"uuid": "a69a42c0-5153-4727-a259-46e20a71889f@6c48a",
"displayName": "home_normal",
"id": "6c48a",
"name": "texture",
"userData": {
"wrapModeS": "clamp-to-edge",
"wrapModeT": "clamp-to-edge",
"minfilter": "linear",
"magfilter": "linear",
"mipfilter": "none",
"anisotropy": 0,
"isUuid": true,
"imageUuidOrDatabaseUri": "a69a42c0-5153-4727-a259-46e20a71889f",
"visible": false
},
"ver": "1.0.22",
"imported": true,
"files": [
".json"
],
"subMetas": {}
},
"f9941": {
"importer": "sprite-frame",
"uuid": "a69a42c0-5153-4727-a259-46e20a71889f@f9941",
"displayName": "home_normal",
"id": "f9941",
"name": "spriteFrame",
"userData": {
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0,
"trimX": 6,
"trimY": 3,
"width": 63,
"height": 69,
"rawWidth": 75,
"rawHeight": 75,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"packable": true,
"pixelsToUnit": 100,
"pivotX": 0.5,
"pivotY": 0.5,
"meshType": 0,
"vertices": {
"rawPosition": [
-31.5,
-34.5,
0,
31.5,
-34.5,
0,
-31.5,
34.5,
0,
31.5,
34.5,
0
],
"indexes": [
0,
1,
2,
2,
1,
3
],
"uv": [
6,
72,
69,
72,
6,
3,
69,
3
],
"nuv": [
0.08,
0.04,
0.92,
0.04,
0.08,
0.96,
0.92,
0.96
],
"minPos": [
-31.5,
-34.5,
0
],
"maxPos": [
31.5,
34.5,
0
]
},
"isUuid": true,
"imageUuidOrDatabaseUri": "a69a42c0-5153-4727-a259-46e20a71889f@6c48a",
"atlasUuid": ""
},
"ver": "1.0.12",
"imported": true,
"files": [
".json"
],
"subMetas": {}
}
},
"userData": {
"hasAlpha": true,
"type": "sprite-frame",
"fixAlphaTransparencyArtifacts": false,
"redirect": "a69a42c0-5153-4727-a259-46e20a71889f@6c48a"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@ -0,0 +1,134 @@
{
"ver": "1.0.27",
"importer": "image",
"imported": true,
"uuid": "5de15a5b-39ad-47de-b9f6-247a4f379169",
"files": [
".json",
".png"
],
"subMetas": {
"6c48a": {
"importer": "texture",
"uuid": "5de15a5b-39ad-47de-b9f6-247a4f379169@6c48a",
"displayName": "home_pressed",
"id": "6c48a",
"name": "texture",
"userData": {
"wrapModeS": "clamp-to-edge",
"wrapModeT": "clamp-to-edge",
"minfilter": "linear",
"magfilter": "linear",
"mipfilter": "none",
"anisotropy": 0,
"isUuid": true,
"imageUuidOrDatabaseUri": "5de15a5b-39ad-47de-b9f6-247a4f379169",
"visible": false
},
"ver": "1.0.22",
"imported": true,
"files": [
".json"
],
"subMetas": {}
},
"f9941": {
"importer": "sprite-frame",
"uuid": "5de15a5b-39ad-47de-b9f6-247a4f379169@f9941",
"displayName": "home_pressed",
"id": "f9941",
"name": "spriteFrame",
"userData": {
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0,
"trimX": 6,
"trimY": 3,
"width": 63,
"height": 69,
"rawWidth": 75,
"rawHeight": 75,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"packable": true,
"pixelsToUnit": 100,
"pivotX": 0.5,
"pivotY": 0.5,
"meshType": 0,
"vertices": {
"rawPosition": [
-31.5,
-34.5,
0,
31.5,
-34.5,
0,
-31.5,
34.5,
0,
31.5,
34.5,
0
],
"indexes": [
0,
1,
2,
2,
1,
3
],
"uv": [
6,
72,
69,
72,
6,
3,
69,
3
],
"nuv": [
0.08,
0.04,
0.92,
0.04,
0.08,
0.96,
0.92,
0.96
],
"minPos": [
-31.5,
-34.5,
0
],
"maxPos": [
31.5,
34.5,
0
]
},
"isUuid": true,
"imageUuidOrDatabaseUri": "5de15a5b-39ad-47de-b9f6-247a4f379169@6c48a",
"atlasUuid": ""
},
"ver": "1.0.12",
"imported": true,
"files": [
".json"
],
"subMetas": {}
}
},
"userData": {
"hasAlpha": true,
"type": "sprite-frame",
"fixAlphaTransparencyArtifacts": false,
"redirect": "5de15a5b-39ad-47de-b9f6-247a4f379169@6c48a"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -3,18 +3,14 @@ const { ccclass, property } = _decorator;
@ccclass('FirstPersonController')
export class FirstPersonController extends Component {
// Если камера находится как дочерняя нода player, можно её оставить для визуального представления,
// но мы не будем отдельно управлять её вращением – вращение задаётся на player.
@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
@ -22,15 +18,18 @@ export class FirstPersonController extends Component {
@property
public maxSpeed: number = 20;
// Вектор движения, обновляемый по нажатию клавиш
// Вектор направления движения
private _moveDirection: Vec3 = new Vec3();
// Храним текущие углы поворота (в градусах) – полное вращение player
// Храним текущие углы поворота (в градусах)
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);
@ -41,6 +40,8 @@ export class FirstPersonController extends Component {
// Инициализируем углы текущей ориентацией ноды player
this._eulerAngles = this.node.eulerAngles.clone();
// Сохраняем начальное положение для эмитации события "moved"
this._lastEmittedPosition = this.node.getPosition().clone();
}
onDestroy() {
@ -52,7 +53,6 @@ export class FirstPersonController extends Component {
input.off(Input.EventType.MOUSE_WHEEL, this._onMouseWheel, this);
}
// Обработка нажатий клавиш – WASD (а также Q/E для движения по оси Y)
private _onKeyDown(event: EventKeyboard) {
switch (event.keyCode) {
case KeyCode.KEY_W:
@ -93,9 +93,8 @@ export class FirstPersonController extends Component {
}
}
// Обработка мыши для вращения
private _onMouseDown(event: EventMouse) {
if (event.getButton() === 0) { // Левая кнопка
if (event.getButton() === 0) {
this._isLeftMousePressed = true;
}
}
@ -108,26 +107,24 @@ export class FirstPersonController extends Component {
private _onMouseMove(event: EventMouse) {
if (this._isLeftMousePressed) {
// Обновляем углы – горизонтальный (yaw) и вертикальный (pitch)
// Обновляем углы поворота: горизонтальный (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
// Применяем поворот к ноде player
const newQuat = new Quat();
Quat.fromEuler(newQuat, this._eulerAngles.x, this._eulerAngles.y, 0);
this.node.setRotation(newQuat);
// Если камера является дочерней нодой player и вы хотите, чтобы она точно следовала за player,
// можно сбросить её локальное вращение (или задать свой offset, если нужно)
// Если камера дочерняя нода, сбрасываем её локальное вращение
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);
@ -138,18 +135,24 @@ export class FirstPersonController extends Component {
}
update(deltaTime: number) {
// Вычисляем направление движения, основываясь на полной (world) ориентации ноды player
// forward и right будут включать и наклон, если он задан
// Вычисляем направление движения с учётом ориентации игрока
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);
// Для вертикального перемещения (Q/E) используем мировую ось вверх
Vec3.scaleAndAdd(move, move, right, this._moveDirection.x * this.moveSpeed * deltaTime);
Vec3.scaleAndAdd(move, move, Vec3.UP, this._moveDirection.y * this.moveSpeed * deltaTime);
// Перемещаем player в мировом пространстве, чтобы направление движения соответствовало ориентации
// Перемещаем игрока в мировом пространстве
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();
}
}
}

View File

@ -0,0 +1,77 @@
import { _decorator, Component, Node, tween, Vec3 } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('ReturnCameraButtonController')
export class ReturnCameraButtonController extends Component {
// Ссылка на кнопку, которую нужно показывать/скрывать
@property(Node)
public returnCameraButton: Node = null!;
// Ссылка на ноду персонажа
@property(Node)
public character: Node = null!;
// Длительность анимации возврата кнопки на исходную позицию
@property
public returnDuration: number = 0.3;
// Длительность анимации скрытия кнопки вниз за экран
@property
public hideDuration: number = 0.3;
// Позиция, куда кнопка скрывается (например, ниже экрана)
@property
public hidePos: Vec3 = new Vec3(0, -100, 0);
// Порог смещения персонажа (в единицах пространства), при котором кнопка появляется
@property
public moveThreshold: number = 1;
// Исходная позиция персонажа
private originalCharacterPos: Vec3 = new Vec3();
// Исходная позиция кнопки
private originalButtonPos: Vec3 = new Vec3();
start() {
// Сохраняем исходную позицию кнопки, как её позицию при отображении (например, в инспекторе)
this.originalButtonPos = this.returnCameraButton.getPosition().clone();
// Сразу смещаем кнопку в скрытое положение
this.returnCameraButton.setPosition(this.hidePos);
// Сохраняем исходную позицию персонажа
this.originalCharacterPos = this.character.getPosition().clone();
// Подписываемся на событие "moved", эмитируемое персонажем при его движении
this.character.on('moved', this.onCharacterMoved, this);
}
// Обработчик события движения персонажа
private onCharacterMoved() {
const currentPos = this.character.getPosition();
const distance = currentPos.clone().subtract(this.originalCharacterPos).length();
if (distance >= this.moveThreshold) {
// Если персонаж сместился достаточно, запускаем анимацию показа кнопки
this.resetPosition();
}
}
// Метод, который возвращает кнопку в исходное положение с анимацией
public resetPosition() {
// Если кнопка деактивирована, активируем её
this.returnCameraButton.active = true;
tween(this.returnCameraButton)
.to(this.returnDuration, { position: this.originalButtonPos })
.start();
}
// Метод для анимации скрытия кнопки вниз за экран и её деактивации
public hideButton() {
tween(this.returnCameraButton)
.to(this.hideDuration, { position: this.hidePos })
.call(() => {
this.returnCameraButton.active = false;
})
.start();
}
}

View File

@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "710e0958-b319-4369-acd1-6b9e1b6d38b1",
"files": [],
"subMetas": {},
"userData": {}
}