2016-09-28 56 views
0

我想爲我在大學的編程類做一個小遊戲,我遇到了一個嘗試創建碰撞矩形的問題。無法創建碰撞矩形

當我嘗試使用我的紋理的寬度和高度。我得到一個錯誤,告訴我我無法從float轉換爲int。但圖像的像素大小不是浮點值?

這裏是我在我的遊戲代碼的對象類(有很多的意見,以幫助指導那裏的東西是爲了去):

class ButtonSprite 
{ 
    public Texture2D Art; 
    public Vector2 Position; 

    public ButtonSprite(Vector2 pos, Texture2D tex) 
    { 
     // Copy the texture "tex" into the "Art" class variable 
     Art = tex; 
     // Copy the vector "pos" into the "Position" class variable 
     Position = pos; 
    } 

    public void DrawMe(SpriteBatch sb, Color col) 
    { 
     // use the spritebatch "sb" to draw the sprite at "Position" using the texture "Art" with the tint from "col" 
     sb.Draw(Art, Position, col); 
    } 
} 

class PlayerSprite 
{ 
    public Texture2D Art; 
    public Vector2 Position; 
    public Rectangle CollisionRect; 

    public PlayerSprite(Vector2 pos, Texture2D tex) 
    { 
     // Copy the texture "tex" into the "Art" class variable 
     Art = tex; 
     // Copy the vector "pos" into the "Position" class variable 
     Position = pos; 
     // create a new CollisionRect Rectangle using the X and Y from Position and the Width and Height from Art 
     CollisionRect = new Rectangle(Position.X, Position.Y, Art.Width, Art.Height); 
    } 

    public void UpdateMe(ButtonState leftB, ButtonState rightB, ButtonState downB, ButtonState upB) 
    { 
     // if leftB is pressed 
     if (leftB == ButtonState.Pressed) 
     { 
      // subtract 1 from the X that belongs to Position 
      Position.X -= 1; 
     } 
     // endif 

     // if rightB is pressed 
     if (rightB == ButtonState.Pressed) 
     { 
      // add 1 to the X that belongs to Position 
      Position.X += 1; 
     } 
     // endif 

     // if downB is pressed 
     if (downB == ButtonState.Pressed) 
     { 
      // add 1 to the Y that belongs to Position 
      Position.Y += 1; 
     } 
     // endif 

     // if upB is pressed 
     if (upB == ButtonState.Pressed) 
     { 
      // subtract 1 from the Y that belongs to Position 
      Position.Y -= 1; 
     } 
     // endif 

     // set the X that belongs to CollisionRect to equal the integer version of the X that belongs to Position 
     // set the Y that belongs to CollisionRect to equal the integer version of the Y that belongs to Position 
    } 

    public void DrawMe(SpriteBatch sb) 
    { 
     // use the spritebatch "sb" to draw the sprite at "Position" using the texture "Art" with a white tint 
     sb.Draw(Art, Position, Color.White); 
    } 
} 
} 
+0

你有一個額外的'}'在你的代碼的末尾你忘記包括'namespace {'部分 – MethodMan

回答

0

馬上蝙蝠,我會建議你算算你的碰撞也使用運動。這將防止更多毛刺(例如穿過牆壁)。

這樣做的一個好方法是通過移動矩形的大小(暫時)給目標矩形充氣。然後,您執行一個線到邊框交叉。這會給你一個交點,同時對毛刺更安全。

0

建立你的碰撞矩形時試試這條線。它會將高度爲&的寬度浮點數轉換爲整數。 + 1是可選的。

CollisionRect = new Rectangle(Position.X, Position.Y, (int)Art.Width + 1, (int)Art.Height + 1);