83 lines
2.3 KiB
C#
83 lines
2.3 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
namespace AibisDream
|
|
{
|
|
public class AbsMobileObject : MonoBehaviour
|
|
{
|
|
[SerializeField] protected MobileObjectData mobileObjectData;
|
|
private Vector3 _initPos;
|
|
|
|
public bool IsActive { get; private set; }
|
|
public float ExistTime { get; private set; }
|
|
public float Speed { get; private set; }
|
|
public event Action<AbsMobileObject> OnDisposed;
|
|
|
|
public virtual void Init()
|
|
{
|
|
transform.position += new Vector3(mobileObjectData.offset.x, mobileObjectData.offset.y, 0);
|
|
_initPos = transform.position;
|
|
gameObject.name = mobileObjectData.itemName;
|
|
IsActive = true;
|
|
Speed = RandomSpeed();
|
|
gameObject.SetActive(true);
|
|
}
|
|
|
|
public void Init(MobileObjectData data)
|
|
{
|
|
mobileObjectData = data;
|
|
Init();
|
|
}
|
|
|
|
protected string RandomSelectAddress()
|
|
{
|
|
return mobileObjectData.assetAddressArray[
|
|
UnityEngine.Random.Range(0, mobileObjectData.assetAddressArray.Length)];
|
|
}
|
|
|
|
protected float RandomSpeed()
|
|
{
|
|
return UnityEngine.Random.Range(mobileObjectData.speed.x, mobileObjectData.speed.y);
|
|
}
|
|
|
|
public void Update()
|
|
{
|
|
// 移动
|
|
if (IsActive)
|
|
{
|
|
var posDelta = mobileObjectData.direction.normalized * (Speed * Time.deltaTime);
|
|
transform.position += new Vector3(posDelta.x, posDelta.y, 0);
|
|
|
|
ExistTime += Time.deltaTime;
|
|
|
|
if (IsReachEnd())
|
|
{
|
|
Dispose();
|
|
}
|
|
}
|
|
}
|
|
|
|
private bool IsReachEnd()
|
|
{
|
|
if (mobileObjectData.isDistanceMode)
|
|
{
|
|
return mobileObjectData.existDistance <= Vector3.Distance(transform.position, _initPos);
|
|
}
|
|
|
|
return mobileObjectData.existTime <= ExistTime;
|
|
}
|
|
|
|
protected virtual void Dispose()
|
|
{
|
|
IsActive = false;
|
|
ExistTime = 0;
|
|
_initPos = default;
|
|
mobileObjectData = default;
|
|
gameObject.name = "Empty";
|
|
gameObject.SetActive(false);
|
|
// 回收
|
|
OnDisposed?.Invoke(this);
|
|
OnDisposed = null;
|
|
}
|
|
}
|
|
} |