IndieGame/client/Assets/Scripts/Role/Player/PlayerController.cs
2024-10-30 17:58:20 +08:00

113 lines
3.6 KiB
C#

using Animancer;
using NodeCanvas.Framework;
using NodeCanvas.StateMachines;
using UnityEngine;
namespace Ether
{
[RequireComponent(typeof(Rigidbody2D))]
public class PlayerController : Entity
{
private Rigidbody2D playerRigid;
private FSMOwner fsmOwer;
private Blackboard blackboard;
private bool isInputEnabled = true;
private void Start()
{
playerRigid = GetComponent<Rigidbody2D>();
fsmOwer = GetComponent<FSMOwner>();
blackboard = GetComponent<Blackboard>();
DontDestroyOnLoad(gameObject);
}
private void OnEnable()
{
EventCenter.AddListener<EtherInputEvent, bool>(EtherInputEvent.Up, OnUp);
EventCenter.AddListener<EtherInputEvent, bool>(EtherInputEvent.Down, OnDown);
EventCenter.AddListener<EtherInputEvent, bool>(EtherInputEvent.Left, OnLeft);
EventCenter.AddListener<EtherInputEvent, bool>(EtherInputEvent.Right, OnRight);
// blackboard.GetVariable<Vector2>("moveDirection").onValueChanged += (value) =>
// {
// if ((Vector2)value == Vector2.zero)
// {
// Debug.LogError("moveDirection zero");
// }
// else
// {
// Debug.LogError("moveDirection :" + (Vector2)value);
// }
// };
}
private void OnUp(bool isDown)
{
Vector2 move = blackboard.GetVariableValue<Vector2>("moveDirection");
move.y = isDown ? move.y + 1 : move.y - 1;
OnMove(move);
}
private void OnDown(bool isDown)
{
Vector2 move = blackboard.GetVariableValue<Vector2>("moveDirection");
move.y = isDown ? move.y - 1 : move.y + 1;
OnMove(move);
}
private void OnLeft(bool isDown)
{
Vector2 move = blackboard.GetVariableValue<Vector2>("moveDirection");
move.x = isDown ? move.x - 1 : move.x + 1;
OnMove(move);
}
private void OnRight(bool isDown)
{
Vector2 move = blackboard.GetVariableValue<Vector2>("moveDirection");
move.x = isDown ? move.x + 1 : move.x - 1;
OnMove(move);
}
private void OnMove(Vector2 move)
{
if (!isInputEnabled)
{
return;
}
if (move == Vector2.zero)
{
blackboard.SetVariableValue("moveDirection", move);
}
else
{
blackboard.SetVariableValue("moveDirection", move);
}
}
public void SetInputOperation(bool isEnable)
{
Vector2 moveDirection = blackboard.GetVariableValue<Vector2>("moveDirection");
if (moveDirection != Vector2.zero)
{
blackboard.SetVariableValue("direction", moveDirection);
blackboard.SetVariableValue("moveDirection", Vector2.zero);
}
isInputEnabled = isEnable;
}
private void OnDisable()
{
//EventCenter.RemoveListener<ReInputEvent, Vector2>(ReInputEvent.Move, OnMove);
EventCenter.RemoveListener<EtherInputEvent, bool>(EtherInputEvent.Up, OnUp);
EventCenter.RemoveListener<EtherInputEvent, bool>(EtherInputEvent.Down, OnDown);
EventCenter.RemoveListener<EtherInputEvent, bool>(EtherInputEvent.Left, OnLeft);
EventCenter.RemoveListener<EtherInputEvent, bool>(EtherInputEvent.Right, OnRight);
}
}
}