Beginer Developer
Beginer Developer

Reputation: 23

Ball line collision

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;

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

}

Upvotes: 0

Views: 889

Answers (1)

Kane
Kane

Reputation: 4147

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.

Upvotes: 1

Related Questions