Table of Contents

Physics, Collisions


Basic Physics: Preliminaries

Position and Velocity

Acceleration

Gravity


Collisions

Collision detection

Bounding box method

Collision test, two methods:

                 public boolean collidesWith (Entity other) 
                 {
                    if (other instanceof RectEntity) {
                       Rectangle him = new Rectangle();
                       me.setBounds((int) x, (int) y, sprite.getWidth(), sprite.getHeight());
                       him.setBounds((int) other.x, (int) other.y, other.sprite.getWidth(), other.sprite.getHeight());
                       return me.intersects(him);
                    }
                    else if (other instanceof CircleEntity) {
                       Ellipse2D him = new Ellipse2D.Double();
                       me.setBounds((int) x, (int) y, sprite.getWidth(), sprite.getHeight());
                       him.setFrame((int) other.x, (int) other.y, other.sprite.getWidth(), other.sprite.getHeight());
                       return him.intersects(me);
                    }
                    else if (other instanceof TriangleEntity) {
                       boolean collided = false;
                       Point2D p1 = ((TriangleEntity)other).p1;
                       Point2D p2 = ((TriangleEntity)other).p2;
                       Point2D p3 = ((TriangleEntity)other).p3;
                       collided = me.intersectsLine(p1.getX(), p1.getY(), p2.getX(), p2.getY()) || 
                        me.intersectsLine(p2.getX(), p2.getY(), p3.getX(), p3.getY()) ||
                        me.intersectsLine(p3.getX(), p3.getY(), p1.getX(), p1.getY());
                       return collided;
                    }
                    else {
                       System.out.println("Other Entity's shape is ambiguous!");
                       return false;
                    }
                 }

Collision response

              if ((ballPoint.x + ballSpeed.x) <= plane.x) {
                  ballSpeed.x = (ballSpeed.x * -1);
              }
              
              if ((ballPoint.x + ballSpeed.x) >= (plane.width)) {
                  ballSpeed.x = (ballSpeed.x * -1);
              }
              
              if ((ballPoint.y + ballSpeed.y) <= plane.y) {
                  ballSpeed.y = (ballSpeed.y * -1);
              }
              
              if ((ballPoint.y + ballSpeed.y) >= (plane.height)) {
                  ballSpeed.y = (ballSpeed.y * -1);
              }

Java 2D Gravity and Collision Examples: