0
\$\begingroup\$

For my game I need to have a circle collide against a wall and bounce off in the appropriate direction. I've looked around for a while and haven't found a good solution to my problem. I have a diagram of what should happen below. vecColl

The problem is that I have the vector V, U, and P, but I am unable to calculate the new X and Y vectors after the collision. I have tried using Trig to find the angle of the intersection and get the new X and Y vectors from that but it gives massive numbers. How do I get the new X and Y vectors easily? Source code is posted below.

for (int i = 0; i < collisionList.size(); i++){
    Vec2<Integer> c = collisionList.get(i);
    int cx = c.getX();
    int cy = c.getY();
    if (distance(x, y, cx, cy) <= (r - (r / 2))){
        float mag = (float)Math.sqrt((Math.pow(x, 2) + Math.pow(y, 2)));
        float angleRad = (float)Math.atan(y / x);

        xVel = (float)(mag * Math.cos(angleRad));
        yVel = (float)(mag * Math.sin(angleRad));
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Get the perpendicular vector of the line direction, mirror the ball velocity to that vector you found. Done! EDIT: in your images, the perpendicular vector of the line direction is U. Q is the mirrored vector of V upon U. \$\endgroup\$ Commented Jun 4, 2015 at 10:00

1 Answer 1

1
\$\begingroup\$

The way I handle these kinds of 2D physics is to process the X and Y components of the vector separately.

That way if a collision occurs, I know which direction the collider was moving along based on the sign and component of the velocity vector I am processing.

Then when a collision occurs, you can modify the velocity on the appropriate axis. Changing the sign simulates a perfectly elastic bounce, while multiplying it by a negative number (eg -0.5) can simluate a bounce where some energy is lost.

For your code

/*
   Move along X Axis
*/

for (int i = 0; i < collisionList.size(); i++){
    Vec2<Integer> c = collisionList.get(i);
    int cx = c.getX();
    int cy = c.getY();
    if (distance(x, y, cx, cy) <= (r - (r / 2))){
        xVel = -xVel;
    }
}

/*
   Move along Y Axis
*/

for (int i = 0; i < collisionList.size(); i++){
    Vec2<Integer> c = collisionList.get(i);
    int cx = c.getX();
    int cy = c.getY();
    if (distance(x, y, cx, cy) <= (r - (r / 2))){
        yVel = -yVel;
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .