Hi there,
I'm a beginner with XNA, and for the sake of personal knowledge i'm trying to create a simple breakout clone (loving the cliche of this). Anyway, this far i'm going ok, but now I have a problem with collision detection between the ball and the windows boundaries.
I also know what is causing this problem, but I dont know how to solve it.
The code has been set up that the ball is stick to the paddle untill you release the ball by hitting space. At this point the ball will move by a pre-set speed (given in the class of the ball) along the Y axis. This works without problems. However, the direction the ball is moving on on the X axis is set pick a random direction. This ransomness is causing the problem with the collisions. When the ball collide with the top or bottom of the screen (the Y axis) everything works perfect and the ball, will bounce back. But when the ball hits one of the side walls (the X axis) the ball sticks against the wall and wont move anymore.
The problem here is the randomness given to the X axis of the bal. If I start the game without thise random code running the ball will bounce against the walls with no problem. But doing this means the ball will not get a random direction at the point it is realeased from the playerpaddle, so the whole point of the game will be gone.
This is the code in the Ball.cs clas file:
public
Vector2 pos = new Vector2(); public float speed; public int direction = 0;
public Ball()
{
pos = new Vector2(0f, 0f);
speed = 5;
Random rand = new Random();
direction = rand.Next(-5, 5);
}
And this is the code in the Game.cs class file that is used to check the collision:
// Handles the balls speed and direction after the ball has been released form the paddle
void BallUpdate(){
if (keyReleased){
ball.pos.Y -= ball.speed;
ball.pos.X -= ball.direction;
}
int MinX = 0; int MaxX = graphics.GraphicsDevice.Viewport.Width - t_ball.Width; int MinY = 0; int MaxY = graphics.GraphicsDevice.Viewport.Height - t_ball.Height;if (ball.pos.X > MaxX)
{
ball.speed *= -1;
ball.pos.X = MaxX;
}
else if (ball.pos.X < MinX)
{
ball.speed *= -1;
ball.pos.X = MinX;
}
if (ball.pos.Y > MaxY)
{
ball.speed *= -1;
ball.pos.Y = MaxY;
}
else if (ball.pos.Y < MinY)
{
ball.speed *= -1;
ball.pos.Y = MinY;
}
}