所以今天我正在学习和实现命令模式来处理对象的输入和移动。
所以我的问题是:
我附加到游戏对象的那个只是InputHandler。这是我的代码,涉及移动一个对象:
这是我的输入处理程序或据我所知的客户端
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));
}
}
Receiver类(我实现了逻辑,即移动)
public enum ACTION_LIST
{
MOVERIGHT,
MOVELEFT
}
public interface IReceiver
{
void Action(ACTION_LIST moves);
}
接收器界面,让事情变得更轻松......
public class MoveRight : Command
{
public MoveRight(IReceiver receiver):base(receiver)
{
}
public override void Execute()
{
receiver.Action(ACTION_LIST.MOVERIGHT);
}
}
具体命令。我只发布了一个动作..
cp
答案 0 :(得分:2)
我不同意Joe Blow和其他人说Unity是一堆脚本而不是OOP。我使用带有单个入口点的主脚本并动态创建所有对象和组件。我甚至使用接口,模拟和单元测试。
因此,使用命令模式是可以的。但是我没有理由在你的情况下使用它。 命令模式可能非常方便,以防您需要一堆命令才能Do()
和Undo()
您的命令(编辑器,策略游戏)。请在此处阅读更多内容:http://gameprogrammingpatterns.com/command.html