0

In my Android game I detected the collision of a ball and line, but I don't know how to change ball velocity in relation with line angle.

if(ball.collidesWith(line)){
    ball.nextTile();
    ball.mPhysicsHandler.setAngularVelocity(65);
    float xvelo=ball.mPhysicsHandler.getVelocityX();
    float yvelo=ball.mPhysicsHandler.getVelocityY();
    double lineAngle = Math.atan2(line.getY2() - line.getY1(), 
                                  line.getX1() - line.getX2()) * 180 / Math.PI;

    ???????????????????????????????

}
  • OoOo this sounds like physics. Hold on I'm taking that class now, I have some notes somewhere around here... – Jack Nov 22 '11 at 14:53
  • 3
    This may get you started: http://stackoverflow.com/questions/345838/ball-to-ball-collision-detection-and-handling – ImR Nov 22 '11 at 14:54
  • is this a physics question (how to calculate new velocity and angle or are you asking how to implement the new velocity and angle? – STT LCU Nov 22 '11 at 14:55
  • The most common way to tackle this sort of problem is to split the ball velocity into 2 perpendicular components - one parallel to the line, and one perpendicular to the line. You can then have 2 scaling factors - one for each of the components - which more or less correlate to how bouncy the ball is, and how much friction there is on the surface of whatever the line represents. Another benefit of this approach is that the maths becomes much simpler - both for your brain and the CPU! – vaughandroid Nov 22 '11 at 15:32

1 Answers1

1

This is more a physics question than a programming question. For any elastic collision (I am assuming you want to keep the same speed on the ball, just change it's direction), the angle of incidence (the angle the ball goes into the line) is the opposite of the angle of reflection (the angle the ball goes away from the line)

So if you have a ball collide with the line, measure the angle between the line and the path of the ball, and the path going away will be (180 - angle-of-incidence) assuming you're using degrees. If you're using radians, it's (2pi - angle-of-incidence).

If your lines are straight up/down or right/left, you can just flip the x/y component of the balls velocity. If not, you'll be doing some trig as described above.

Kane
  • 4,047
  • 2
  • 24
  • 33