Files
MRCS/Assets/_MrCs/Scripts/Item/AirdropPlane.cs

84 lines
2.1 KiB
C#

using System.Collections;
using Mirror;
using UnityEngine;
public class AirdropPlane : NetworkBehaviour
{
public float flySpeed = 20f; // 飞行速度
public int dropCount = 4; // 投放次数
private Vector3 _startPos;
private Vector3 _targetPos;
private bool _started = false;
private float _totalDistance;
private float _nextDropDistance;
/// <summary>
/// 服务器端调用,初始化飞机
/// </summary>
[Server]
public void OnSpawn( Vector3 targetPos)
{
_startPos = transform.position;
_targetPos = targetPos;
transform.LookAt(targetPos);
_totalDistance = Vector3.Distance(_startPos, _targetPos);
_nextDropDistance = _totalDistance / (dropCount + 1);
_started = true;
}
void Update()
{
if (!isServer || !_started) return;
// 飞向目标
transform.position = Vector3.MoveTowards(transform.position, _targetPos, flySpeed * Time.deltaTime);
// 检测是否需要投放
CheckDrop();
// 到达目标点后销毁
if (Vector3.Distance(transform.position, _targetPos) < 0.5f)
{
GameManager.Ins.StartAirDrop();
NetworkServer.Destroy(gameObject);
}
}
float passedDistance = 0f;
float lastPosCheckTime = 0f;
Vector3 lastPos;
private void CheckDrop()
{
// 初次记录
if (lastPosCheckTime == 0)
{
lastPos = transform.position;
lastPosCheckTime = 1;
return;
}
// 累计走过的距离
passedDistance += Vector3.Distance(lastPos, transform.position);
lastPos = transform.position;
// 达到投放位置
if (passedDistance > _nextDropDistance && dropCount > 0)
{
passedDistance = 0;
dropCount--;
int itemId=Random.Range(0, GameManager.Ins.GunInfos.Count);
GameManager.Ins.CreateAirDropItem((GunType)itemId, transform.position);
// 计算下一段距离
_nextDropDistance = _totalDistance / (dropCount + 1);
}
}
}