🥙功能描述
提供停止和运动两种状态触发,从moving=>stop
触发stop事件,从stop=>moving
触发moving事件(用到了UniRx插件)
🥩代码
public UnityEvent<State> onStateChangeEvent = new UnityEvent<State>();
public UnityEvent onStopEvent = new UnityEvent();
public UnityEvent onMovingEvent = new UnityEvent();
public enum State
{
none,
stop,
moving
}
State mState = State.none;
public State CurrentState { get => mState; set => mState = value; }
private double checkInterval=0.5f;
private IDisposable checkDis;
private Vector3 lastWpos;
private Vector3 currentWpos;
private Camera cam;
private float movingStep = 0.1f;
private Vector3 lastRotation;
private Vector3 currentRotation;
public Camera Cam
{
get
{
if (cam == null)
{
cam = Camera.main;
}
return cam;
}
}
void OnEnable()
{
base.MyOnEnable();
UpdateLastParam();
CheckUpdate();
this.checkDis = Observable.Interval(TimeSpan.FromSeconds(checkInterval))
.Subscribe(_ =>
{
CheckUpdate();
})
.AddTo(this);
}
void OnDisable()
{
base.MyOnDisable();
checkDis?.Dispose();
}
private void UpdateLastParam()
{
lastWpos = Cam.transform.position;
lastRotation = Cam.transform.rotation.eulerAngles;
}
private void CheckUpdate()
{
UpdateCurrentParam();
if (IsMoving()==true)
{
SwitchMovingState();
}
else
{
SwitchStopState();
}
UpdateLastParam();
}
private void SwitchStopState()
{
if (CurrentState != State.stop)
{
CurrentState = State.stop;
onStateChangeEvent?.Invoke(CurrentState);
onStopEvent?.Invoke();
Debug.Log($"切换到:{CurrentState.ToString()}");
}
}
private void SwitchMovingState()
{
if (CurrentState != State.moving)
{
CurrentState = State.moving;
onStateChangeEvent?.Invoke(CurrentState);
onMovingEvent?.Invoke();
Debug.Log($"切换到:{CurrentState.ToString()}");
}
}
private bool IsMoving()
{
var smPos = Vector3.SqrMagnitude(lastWpos - currentWpos);
var smRotation = Vector3.SqrMagnitude(lastRotation - currentRotation);
return smPos >= movingStep || smRotation >= movingStep;
}
private void UpdateCurrentParam()
{
currentWpos = Cam.transform.position;
currentRotation = Cam.transform.rotation.eulerAngles;
}