所以今天我正在學習和實現Command Patterns來處理對象的輸入和移動。命令模式是否足夠有效,它的具體好處是什麼?
所以我的問題是:
- 我收到的指令模式的執行權或是否需要修改?如果是這樣,有人可以給我一個小例子來改善它。
- 我知道它改善了代碼的可重用性。但是當我使用一個簡單的MovementScript.cs到我的遊戲對象組件時,它會產生什麼樣的差異?難道它不僅僅是相同的,而是花更少的時間來編寫而不是製作一個完整的命令模式?
我附加到gameobject的只有InputHandler。這裏是我的代碼,其中包括移動對象:
這是我的輸入處理程序或就我所知道的客戶
public class InputHandler : MonoBehaviour
{
GameObject theObject;
public Command buttonA, buttonD;
public float acceleration, maxSpeed;
Movement moves;
void Awake()
{
theObject = gameObject;
moves = new Movement(theObject, acceleration, maxSpeed);
}
void Start()
{
buttonA = new MoveLeft(moves);
buttonD = new MoveRight(moves);
}
void Update()
{
HandleInput();
}
public void HandleInput()
{
if (Input.GetKey(KeyCode.A))
{
buttonA.Execute();
}
else if (Input.GetKey(KeyCode.D))
{
buttonD.Execute();
}
}
}
命令抽象類
public abstract class Command
{
//The Receiver of the command..
protected IReceiver receiver = null;
public Command(IReceiver receiver)
{
this.receiver = receiver;
}
public abstract void Execute();
}
接收器類(我實現邏輯,這是運動)
public class Movement : IReceiver
{
public ACTION_LIST currentMoves;
private GameObject theObject;
private float acceleration;
private float maxspeed;
public Movement(GameObject theObject, float acceleration, float maxspeed)
{
this.theObject = theObject;
this.acceleration = acceleration;
this.maxspeed = maxspeed;
}
public void Action(ACTION_LIST moves)
{
if (moves == ACTION_LIST.MOVERIGHT)
MoveRight(theObject);
else if (moves == ACTION_LIST.MOVELEFT)
MoveLeft(theObject);
}
public void MoveRight(GameObject obj)
{
obj.GetComponent<Rigidbody2D>().AddForce(new Vector2(acceleration, obj.GetComponent<Rigidbody2D>().velocity.y));
}
public void MoveLeft(GameObject obj)
{
obj.GetComponent<Rigidbody2D>().AddForce(new Vector2(-acceleration, obj.GetComponent<Rigidbody2D>().velocity.y));
}
}
接口接收器,以使事情更容易..
public enum ACTION_LIST
{
MOVERIGHT,
MOVELEFT
}
public interface IReceiver
{
void Action(ACTION_LIST moves);
}
具體命令。我只貼了運動的1 ..
public class MoveRight : Command
{
public MoveRight(IReceiver receiver):base(receiver)
{
}
public override void Execute()
{
receiver.Action(ACTION_LIST.MOVERIGHT);
}
}
這也許是一個很好的問題[代碼審查](http://codereview.stackexchange.com/) –
除了每個人都是天真的,沒有人理解ECS系統:)令人尷尬的是,在代碼審查方面,人們會開始試圖封裝它(就像Deni所說的那樣),並沒有意識到它是一個已經內置於Unity *的完全微不足道的操作。 – Fattie
在Unity中如何做到這一點的完整說明:幸運的是它很容易http://stackoverflow.com/a/35891919/294884 – Fattie