你可以同時使用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
。
我的遊戲對象通常還含有方法繪製自己,比如你Game.Update()
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
spriteBatch.Draw(this._texture, this.Position, Color.White);
}
碰撞檢測代碼,可以只使用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()
與PositionRectangle
,你應該不會注意到太多的區別。
當你和標量的工作,始終使用十進制數。或者如果你的速度是0.1f,並且你不斷將它添加到int,那麼位置將保持不變。但隨着浮動,這將使你的位置不斷增加。 –
@patryk - 除了簡單的屏幕像素位置之外,Vector2還用於其他許多事情。大多數其他用途涉及算術,其精度要比整數更精細。 –