0
天兒真好所有,XNA選擇Game.Components的分組
我的小遊戲有5個彈跳球和1名球員。最初,我第一次寫的彈跳球代碼和每個球發生碰撞檢測方法:
foreach (Bouncer bouncer in Game.Components) //For each bouncer component in the game...
{
if (bouncer != this)// Don't collide with myself
{
if (bouncer.collisionRectangle.Intersects(this.collisionRectangle))
{
// How far apart of the positions of the top right hand corners of the sprites when they hit?
int deltaX = Math.Abs((int)this.position.X - (int)bouncer.position.X);
int deltaY = Math.Abs((int)this.position.Y - (int)bouncer.position.Y);
// This is the width and height of a sprite so when two sprites touch this is how far the corners are from each other.
int targetWidth = 80;
int targetHeight = 80;
// The following determins the type of collision (vert hit vs horiz hit)
// Because the app is driven by a game based timer the actual amount of sprite overlap when the collision detection occurs is variable.
// This bit of simple logic has a 10 pixel tollerance for a hit.
// If target - delta is > 10 it will be interpreted as overlap in the non-colliding axis.
// If both if statements are triggered it is interpreted as a corner collision resulting in both sprites rebounding back along the original paths.
if (targetWidth - deltaX < 10) // The hit is a side on hit.
{
this.velocity.X *= -1;
}
if (targetHeight - deltaY < 10) // The hit is a vertical hit
{
this.velocity.Y *= -1;
}
this.numberOfCollisions = this.numberOfCollisions + 1;
}
}
}
base.Update(gameTime);
}
然後我說我的播放器組件和車輪掉了下來。該應用程序編譯OK,但是當我運行它,我得到一個InvalidCastException和消息:
Unable to cast object of type 'Bounce2.Player' to type 'Bounce2.Bouncer'.
我並不想在此碰撞檢測玩家的對象。
有沒有一種方法,我可以列舉我的方式,通過彈跳對象,並排除任何其他對象?
感謝, 安德魯。
謝謝你。這正是我需要的。助教。 – 2012-01-13 12:26:20