0
\$\begingroup\$

I'm currently working on a demo-type program involving bouncing objects. Currently, I have a rectangle that can bounce around the screen.
When the rectangle bounces against one of the walls imperfectly, part of it will clip into the side of the window (or other objects, in the future).
I'd like to have the rectangle bounce from an accurate position (as in when/where it begins to collide with the object). Is there a better or more efficient way to do this other than by going back a step and checking over again with smaller steps?

The relevant code is here, and for reference the rectangle's velocity is stored as an angle and speed.

    //Update position
    rect.setX(rect.getX() + (rect.getVelocity() * Math.cos(rect.getDirection())));
    rect.setY(rect.getY() + (rect.getVelocity() * Math.sin(rect.getDirection())));

    //Check for collisions
    for(Collider c : colliders) {
        if(c.isColliding(rect)) {
            bounce(rect, c);
            System.out.printf("Rect is colliding with %s%n", c);
        }
    }

Any help would be appreciated.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Although the updated version of the question hasn't been answered, I figured out a solution to the original question. The updated code is here:

    //Update position
    double delX = rect.getVelocity() * Math.cos(rect.getDirection()),
           delY = rect.getVelocity() * Math.sin(rect.getDirection());

    rect.setX(rect.getX() + delX);
    rect.setY(rect.getY() + delY);

    //Check for collisions
    for(Collider c : colliders) {
        if(c.isColliding(rect)) {
            //We found a collision, so now we need to do smaller steps.
            rect.setX(rect.getX() - delX);
            rect.setY(rect.getY() - delY);

            double sDelX = Math.cos(rect.getDirection()),
                   sDelY = Math.sin(rect.getDirection());

            //Loop over small steps (with velocity 1)
            while(!c.isColliding(rect)) {
                rect.setX(rect.getX() + sDelX);
                rect.setY(rect.getY() + sDelY);
            }

            bounce(rect, c);
            System.out.printf("Rect is colliding with %s%n", c);
        }
    }
\$\endgroup\$

You must log in to answer this question.

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