I am trying to have bitmap reflect/bounce when it hits the sides of a window.
Basically, I want to initialise the bitmap to move (shown by BallSpeedX/Y). When it hits the top or bottom it should change direction (BallSpeedY should be inverted). Currently when the bitmap hits the wall, it changes its Y direction briefly before reverting to the original direction. Is there a way I can initialise the X and Y speed, but once it hits the wall keep the new direction (such as in a while loop)?
int BallSpeedX = 3;
int BallSpeedY = 5;
public void Draw(Window screen)
{
_PlayerBitmap.Draw(X,Y);
X += BallSpeedX;
// Y += BallSpeedY;
_PlayerBitmap.Draw(X,Y);
if (Y < screen.Height)
{ //Off bottom
Y += BallSpeedY *-1;
_PlayerBitmap.Draw(X,Y);
}
if (Y > screen.Height)
{ //Off top
Y += BallSpeedY *-1;
_PlayerBitmap.Draw(X,Y);
}
}
The speed is a 2D-vector, so whenever the "ball" hits an edge, you should change the sign of the related coordinate.
int BallSpeedX = 3;
int BallSpeedY = 5;
int ballWidth = 10;
int ballHeight = 10;
public void Draw(Window screen)
{
X += BallSpeedX;
if (X <= 0) {
BallSpeedX = -BallSpeedX;
X = 0;
}
else if (X >= (screen.Width - ballWidth)) {
BallSpeedX = -BallSpeedX;
X = screen.Width - ballWidth;
}
/// (same for Y-coords)
_PlayerBitmap.Draw(X,Y);
}
This is a very simplified version, but I think it should be a good strarting point.