2012-05-05 61 views
2

爲什麼Vector2(來自XNA的庫)使用float而不是int爲什麼Vector2(來自XNA的庫)使用float而不是int?

計算機屏幕上的位置以像素爲單位給出,以便光標位置可由兩個int egers定義。沒有像半像素這樣的東西。爲什麼我們使用花車呢?

In SpriteBatch class我找到了7種重載方法Draw。其中兩個:

public void Draw(Texture2D texture, Rectangle destinationRectangle, Color color); 
public void Draw(Texture2D texture, Vector2 position, Color color); 

所以我們可以看到,繪製同時接受INT浮動座標。

當我執行遊戲對象的屏幕座標時,遇到了這個問題。我認爲矩形是保存物體大小和屏幕座標的好選擇。但現在我不確定...

+0

當你和標量的工作,始終使用十進制數。或者如果你的速度是0.1f,並且你不斷將它添加到int,那麼位置將保持不變。但隨着浮動,這將使你的位置不斷增加。 –

+0

@patryk - 除了簡單的屏幕像素位置之外,Vector2還用於其他許多事情。大多數其他用途涉及算術,其精度要比整數更精細。 –

回答

5

在數學上,矢量是一個運動,而不是一個位置。雖然屏幕上的位置在技術上可能不能在整數之間,但運動肯定可以。如果一個矢量使用int秒,那麼你可以移動的最慢的將是(1, 1)。使用float s,您可以移動(.1, .1),(.001, .001),依此類推。

(另請注意,XNA結構Point並實際使用int秒)

3

這樣的事情,「半個像素」。使用非像素對齊的浮點座標將導致您的精靈在亞像素座標處呈現。這通常是使對象看起來順暢滾動所必需的,但在某些情況下它也會產生不愉快的閃爍效果。

看到這裏的基本思想的總結:Subpixel rendering

+0

那麼我應該用什麼結構來記住對象的大小(在__float__中)和屏幕座標(也是__float__)。 **矩形**是完美的,但它使用__int__。我正在尋找__float__ **矩形**相當於沒有創建自己的結構(我不想重新發明輪子,如果你知道我的意思;))。 –

+0

在我的2D遊戲中,我通常只使用Vector2作爲位置,使用Rectangle作爲邊界,就像NikoDrašković在他的答案中所描述的一樣。 –

4

你可以同時使用Vector2Rectangle來代表你的對象的座標。我通常不喜歡這樣寫道:

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,你應該不會注意到太多的區別。

相關問題