您可以同时使用Vector2
和Rectangle
来表示您的对象坐标。我通常这样做:
public class GameObject
{
Texture2D _texture;
public Vector2 Position { get; set; }
public int Width { get; private set; } //doesn't have to be private
public int Height { get; private set; } //but it's nicer when it doesn't change :)
public Rectangle PositionRectangle
{
get
{
return new Rectangle((int)Position.X, (int)Position.Y, Width, Height);
}
}
public GameObject(Texture2D texture)
{
this._texture = texture;
this.Width = texture.Width;
this.Height = texture.Height;
}
}
要移动对象,只需将其Position
属性设置为新值。
_player.Position = new Vector2(_player.Position.X, 100);
您不必担心矩形,因为它的值直接取决于Position
.
我的游戏对象通常也包含绘制自己的方法,例如
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
spriteBatch.Draw(this._texture, this.Position, Color.White);
}
您的碰撞检测代码Game.Update()
可以只使用PositionRectangle
来测试碰撞
//_player and _enemy are of type GameObject (or one that inherits it)
if(_player.PositionRectangle.Intersects(_enemy.PositionRectangle))
{
_player.Lives--;
_player.InvurnerabilityPeriod = 2000;
//or something along these lines;
}
您也可以调用spriteBatch.Draw()
with PositionRectangle
,您应该不会注意到太大的区别。