0
votes

i have a fixed rectangle. When ball hits a vertex of a triangle, i calculate tangent at point of contact(rectangle vertex). Then i rotate Velocity vector to coincide with the tangent, flip the y value of velocity and rotate it back. Here is my code for top-left corner:

double c1x=rec.x-ball.getX();
double c1y=rec.y-ball.getY();
if(c1*c1+c2*c2<ball.getRadius()*ball.getRadius())
    {
        double angle=Math.atan2(-c1x,c1y); //angle made by tangent
        Vector2D v=ball.velocity.rotate(angle); //rotate velocity vector by 'angle'
        if(v.y<0.0f)     //ball is already moving away from corner
            return;
        v.setY(-v.y);    //flip y
        ball.velocity=v.rotate(-angle);   //rotate back
        return;

    }

But this code doesnot works. When ball strikes the corner it gets stuck, moves along the top edge and then falls off, not bouncing back. Am i doing it correct?

1

1 Answers

0
votes

Making some guesses about your conventions, I suggest this:

double angle=Math.atan2(-c1x,-c1y);

If that doesn't work, we can do some experiments to figure out what's actually going on.

EDIT:

All right, we must build up from simpler solutions. Try these experiments:

1) Set velocity to (0,1) and verify that the ball moves straight up after the collision.

2) Set velocity to (-1,1) and verify that the ball moves up and leftward.

If those work as expected, then pick a trajectory that you would expect to behave in a normal way, such as approaching from above and to the left, then rebounding almost straight up but slightly leftward, then run it through your code but print out all the values in the collision and tell us what they are. That's at least c1x, c1y, angle, and the values of velocity initially and after each rotation.You'll probably notice where things go screwy, and if you don't we will.