我正在尝试在C#中制作游戏。 首先看到一些到目前为止我的代码:同时将对象投射到抽象类和接口上
我的抽象类gridobject
它包含了我的gridobjects(墙,播放器,敌人,等等)的所有一般属性
abstract class GridObject
{
public Rectangle Rect;
...
//all kind of getters and setters for location and size: X, Y, Height, Width
...
}
接口移动
此接口包含移动的网格对象的属性:
interface Moving
{
int Xspeed { get; set; }
int Yspeed { get; set; }
void Move();
}
现在我想重力添加到我的游戏:
public void doGravity(GridObject obj)
{
//check if intersects && if object isn't the same as the given object.
while (AllGridObjects.FindAll(item => item.Rect.IntersectsWith(obj.Rect) && item != obj).Count > 0)
{
obj.Y += obj.Yspeed;
obj.Yspeed++;
}
}
这ofcourse给出了一个编译错误。因为Yspeed不是抽象类GridObject中的必需字段。 也许标题不正确,也许也是我的问题,但是如何将对象投射到抽象类和界面以确保属性Y和属性Yspeed是必需的? 这样做的正确方法是什么?
创建一个'Moving'类型的局部变量?注意:.net约定为接口使用'I'前缀,它应该是'IMoving'而不是'Moving'。 – 2014-10-27 13:49:18
如果我使用两个变量,我的代码是否仍然运行得足够快?并感谢您的提示! – 2014-10-27 13:54:44
当然,试试吧。确保你没有在循环中进行投射。让“IMoving”本地在循环之外。 – 2014-10-27 13:57:58