116 lines
3.5 KiB
C#
116 lines
3.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading;
|
|
using Cysharp.Threading.Tasks;
|
|
using DG.Tweening;
|
|
using Game.Pathfinding;
|
|
using Game.Spine;
|
|
using Sirenix.OdinInspector;
|
|
using Spine.Unity;
|
|
using UnityEngine;
|
|
|
|
namespace Game.Player
|
|
{
|
|
[RequireComponent(typeof(SpineAnimator))]
|
|
class PlayerInfo : MonoBehaviour
|
|
{
|
|
[SerializeField] [ReadOnly] private Player _player;
|
|
[SerializeField] private float speed = 1f;
|
|
[SerializeField] private Vector2 birthPoint;
|
|
[SerializeField] private SpineAnimator _animator;
|
|
|
|
private void Awake()
|
|
{
|
|
_animator = this.GetComponent<SpineAnimator>();
|
|
}
|
|
|
|
public void SetPlayer(Player player)
|
|
{
|
|
this._player = player;
|
|
this.gameObject.name = this._player.playerName;
|
|
transform.position = birthPoint;
|
|
}
|
|
|
|
public async UniTask<bool> MoveAsync(List<WayPoint> wayPoint, Vector2 endPos, CancellationToken token)
|
|
{
|
|
_animator.PlayAni("walk", true);
|
|
|
|
// enter this room
|
|
foreach (var point in wayPoint)
|
|
{
|
|
await this.MoveAsync(point.position, token);
|
|
}
|
|
|
|
// enter room a point
|
|
await this.MoveAsync(endPos, token);
|
|
_animator.PlayAni("idle", true);
|
|
|
|
return true;
|
|
}
|
|
|
|
async UniTask MoveAsync(Vector2 endPos, CancellationToken token)
|
|
{
|
|
var position = transform.position;
|
|
var distance = Vector3.Distance(position, endPos);
|
|
var time = distance / this.speed;
|
|
|
|
CheckIsNeedTurn(position, endPos);
|
|
|
|
transform.DOMove(endPos, time).SetEase(Ease.Linear);
|
|
float delayTimeSpan = time * 1000;
|
|
await UniTask.Delay((int)delayTimeSpan); // (int)delayTimeSpan
|
|
|
|
// Debug.Log($"time is {time}, await time is {delayTimeSpan}");
|
|
}
|
|
|
|
public void JumpTo(Vector2 endPos)
|
|
{
|
|
transform.position = endPos;
|
|
}
|
|
|
|
#region Add Test
|
|
|
|
private float startTime; // 开始移动的时间
|
|
private float journeyLength; // 移动的总距离
|
|
|
|
async UniTask MoveToAsync(Vector2 end, CancellationToken token)
|
|
{
|
|
journeyLength = Vector3.Distance(transform.position, end);
|
|
startTime = Time.time;
|
|
|
|
while (true)
|
|
{
|
|
// 计算从开始移动到现在所经过的时间
|
|
float journeyTime = Time.time - startTime;
|
|
// 计算当前位置所在的百分比
|
|
float fracJourney = journeyTime / journeyLength;
|
|
// 使用线性插值计算当前位置
|
|
transform.position = Vector2.Lerp(transform.position, end, fracJourney * this.speed);
|
|
|
|
// 如果当前位置接近于目标位置,停止移动
|
|
if (fracJourney >= 0.1f)
|
|
{
|
|
// 将物体位置设置为目标位置,确保准确到达目标点
|
|
transform.position = end;
|
|
break;
|
|
}
|
|
|
|
await UniTask.Yield();
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
void CheckIsNeedTurn(Vector2 str, Vector2 end)
|
|
{
|
|
if (str.x > end.x)
|
|
{
|
|
transform.localEulerAngles = new Vector3(0, 180, 0);
|
|
}
|
|
else if (str.x < end.x)
|
|
{
|
|
transform.localEulerAngles = new Vector3(0, 0, 0);
|
|
}
|
|
}
|
|
}
|
|
} |