我不知道你是如何封装球逻辑的,但这是我可能会尝试的方式。使用这样的类可以保证球的所有内部逻辑都在一个位置,以便可以根据位置和边界预测生成的绘图矩形。使用vector2不再有消失的球!
public class Ball
{
private Vector2 _position;
private Vector2 _velocity;
private Point _bounds;
public Vector2 Position { get { return _position; } set { _position = value; } }
public Vector2 Velocity { get { return _velocity; } set { _velocity = value; } }
public int LeftSide { get { return (int)_position.X - (_bounds.X / 2); } }
public int RightSide { get { return (int)_position.X + (_bounds.X / 2); } }
public Rectangle DrawDestination
{
get
{
return new Rectangle((int)_position.X, (int)_position.Y, _bounds.X, _bounds.Y);
}
}
public Ball(Texture2D ballTexture)
{
_position = Vector2.Zero;
_velocity = Vector2.Zero;
_bounds = new Pointer(ballTexture.Width, ballTexture.Height);
}
public void MoveToCenter()
{
_position.X = 400.0f;
_position.Y = 250.0f;
}
public void Update(GameTime gameTime)
{
_position += _velocity;
}
}
然后在您的更新/绘制代码中:
class Game
{
void Update(GameTime gameTime)
{
// ...
ball.Update(gameTime);
if(ball.LeftSide < LEFT_BOUNDS)
{
score.blueScore++;
ball.MoveToCenter();
}
if(Ball.RightSide > RIGHT_BOUNDS)
{
score.greenScore++;
ball.MoveToCenter();
}
// ...
}
void Draw(GameTime gameTime)
{
// ...
_spriteBatch.Draw(ballTexture, ball.DrawDestination, Color.White);
// ...
}
}
记住还要通过经过的帧时间来调节球的速度。