我使用单个精灵表图像作为我的突破游戏的主要纹理。图像是这样的:
我的代码有点混乱,因为我从同一个纹理创建两个元素,使用 aPoint
表示元素大小及其在图纸上的位置, aVector
表示其在视口上的位置, aRectangle
表示元素本身。
Texture2D sheet;
Point paddleSize = new Point(112, 24);
Point paddleSheetPosition = new Point(0, 240);
Vector2 paddleViewportPosition;
Rectangle paddleRectangle;
Point ballSize = new Point(24, 24);
Point ballSheetPosition = new Point(160, 240);
Vector2 ballViewportPosition;
Rectangle ballRectangle;
Vector2 ballVelocity;
我的初始化也有点混乱,但它按预期工作:
paddleViewportPosition = new Vector2((GraphicsDevice.Viewport.Bounds.Width - paddleSize.X) / 2, GraphicsDevice.Viewport.Bounds.Height - (paddleSize.Y * 2));
paddleRectangle = new Rectangle(paddleSheetPosition.X, paddleSheetPosition.Y, paddleSize.X, paddleSize.Y);
Random random = new Random();
ballViewportPosition = new Vector2(random.Next(GraphicsDevice.Viewport.Bounds.Width), random.Next(GraphicsDevice.Viewport.Bounds.Top, GraphicsDevice.Viewport.Bounds.Height / 2));
ballRectangle = new Rectangle(ballSheetPosition.X, ballSheetPosition.Y, ballSize.X, ballSize.Y);
ballVelocity = new Vector2(3f, 3f);
和图纸:
spriteBatch.Draw(sheet, paddleViewportPosition, paddleRectangle, Color.White);
spriteBatch.Draw(sheet, ballViewportPosition, ballRectangle, Color.White);
问题是我无法正确检测到碰撞,使用以下代码:
if(ballRectangle.Intersects(paddleRectangle))
{
ballVelocity.Y = -ballVelocity.Y;
}
我究竟做错了什么?