あなたのオブジェクトの座標を表すためにVector2
とRectangle
の両方を使用することができます。ちょうど新しい値にそのPosition
プロパティを設定し、オブジェクトを移動するには
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;
}
}
:私は通常、このようにそれを行います。
_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);
}
衝突検出コードとして自分自身を描画する方法は、ちょうど衝突あなたも呼び出すことができます
//_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;
}
をテストするためにPositionRectangle
を使用することができます含まれていますspriteBatch.Draw()
をPositionRectangle
とすると、大きな違いはありません。
は、常に小数を使用しています。または速度が0.1fで、それをintに追加し続けると、位置は変わりません。しかし、浮動小数点数を使用すると、ポジションが増加し続けることになります。 –
@patryk - Vector2は、単にピクセル位置をスクリーンするだけでなく、他の多くのものに使用されます。他の用途のほとんどは、整数より細かい精度が望まれる算術演算を含む。 –