Search code examples
jmonkeyengine

How to detect the intersections between 2 nodes in jMonkey


I'm working on a java project; "car game" and I want to detect collisions between the car and any object ("Node"); such as cones on the road.

Similar to this tutorial; http://jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello_picking

The tutorial shows finding the intersection between a ray and the node which has the boxes attached to it. I want to replace the ray with the car chassis for intersection detection.


Solution

  • Assume you have two collidables a and b and want to detect collisions between them. The collision parties can be Geometries, Nodes with Geometries attached (including the rootNode), Planes, Quads, Lines, or Rays. An important restriction is that you can only collide geometry vs bounding volumes or rays. (This means for example that a must be of Type Node or Geometry and b respectively of Type BoundingBox, BoundingSphere or Ray.)

    The interface com.jme3.collision.Collidable declares one method that returns how many collisions were found between two Collidables: collideWith(Collidable other, CollisionResults results).

    Code Sample:

    // Calculate detection results
      CollisionResults results = new CollisionResults();
      a.collideWith(b, results);
      System.out.println("Number of Collisions between" + 
          a.getName()+ " and " + b.getName() + ": " + results.size());
      // Use the results
      if (results.size() > 0) {
        // how to react when a collision was detected
        CollisionResult closest  = results.getClosestCollision();
        System.out.println("What was hit? " + closest.getGeometry().getName() );
        System.out.println("Where was it hit? " + closest.getContactPoint() );
        System.out.println("Distance? " + closest.getDistance() );
      } else {
        // how to react when no collision occured
      }
    }
    

    I think you need also to read this tutorial

    http://hub.jmonkeyengine.org/wiki/doku.php/jme3:advanced:collision_and_intersection

    Hope this helps.