Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: I need help with this game i am trying to make.  (Read 6826 times)

0 Members and 1 Guest are viewing this topic.

Dimple

  • Newbie
  • *
  • Posts: 30
    • View Profile
I need help with this game i am trying to make.
« Reply #15 on: May 10, 2011, 11:15:01 am »
How are you moving the ball? Are you using the ballAngle-variable anywhere else?

Anyway, the problem with the bouncing is that it does exactly what you tell it to do. ;) You aren't actually calculating the angle in which it should bounce off the bat, you are just using whatever is in ballAngle as the angle.
Code: [Select]

// Check collision between Bat and ball

if (Collision(PlayerBat, Ball))
{
    // Calculate the correct angle here (ballAngle = ...)
    Ball.Move(cos((ballAngle/180)*PI) * ballSpeed, sin((ballAngle/180)*PI) * ballSpeed);  // Move the ball
}

How to calculate the correct angle is a whole different story. First you need to decide how you want the ball to bounce off the bat. Do you want it to be realistic (mirror reflection), or do you want it to bounce straight back if the ball hits the center and bounce to the left if it hits to the left etc.?

In every case you have to figure out which side of the rectangle the ball hits (you might even need the exact spot).
Code: [Select]

// As an example, I show you how to find out if the ball hit the bat from above or below.
// I assume that the bat is drawn from the upper left corner. ballCenter simply means the center of the ball (I could've assumed that the ball is drawn
// from the upper left corner, too, but it would've made the code messier).

// Basically just test if the ball is inside the area limited by the left and right sides of the rectangle and then find out
// whether the ball is above or below the rectangle.
// (This won't work correctly if the ball moves so fast that center of the ball is inside the rectangle when this check is performed.)

if(ballCenter.x > bat.x && ballCenter.x < bat.x + bat.width && ballCenter.y < bat.y) {

    // The ball hit the bat from above

} else if(ballCenter.x > bat.x && ballCenter.x < bat.x + bat.width && ballCenter.y > bat.y + bat.height) {

    // The ball hit the bat from below

}

(I haven't tested the example but it should be correct)

The cleanest solution to implement the realistic bouncing is to use vectors. It can be done with trigonometry, too, but it's a bit messier since there are special cases to consider.

Here's your homework: make your game recognize which side of the rectangle the ball hits (and make somehow sure that it works). After that we'll focus on the actual bouncing. If you have trouble with it, don't hesitate to ask. It's completely possible that I have made a mistake somewhere. :)

 

anything