Thursday, June 21, 2012

Terrain Collision detection

Today I implemented collision detection between the camera and the terrain.  Here is a short clip showing this collision detection in action:


To do this, I added an invisible shape (a capsule, but it could be anything really) to the scene graph that I use as the camera's physical space representation.  By that, i mean that object takes up as much space as the camera and it's vehicle take up, and I simply move this object around and use JME3's built in collision detection mechanic to see where that object is able to move.  Then I just manually moved the camera to this invisible object's location, and it is as if the camera had collision detection itself.

The part that I had the most trouble with was hooking up my own camera physics class with JME3's collision detection mechanics.  With a bit of trial and error, I found the best way to do this was to just use JME3's CharacterControl class, which has a very simple physics engine that mimics a player-character's movement. What I did was to send my own physics engine's movement calculation to it, which act as a suggestion on where to go, and the CharacterControl will then tell if that is a viable movement and either go there or not.  Then I just update my own physics engine with the results of the CharacterControl.  Here is my moveCamera code, which is called from the main update loop, to hopefully help explain:

public void moveCamera(Vector3f move, float rotation){
        //remember the previous position vector.
        positionVectorClone = positionVector.clone();
        //Movement
        positionVector = positionVector.add(move);
**this is the CharacterControl**
        //move the physics body, walk in the direction of the difference
        //between the original position vector and the news one.
        cameraPhysicsBody.setWalkDirection(positionVector.subtract(positionVectorClone));
       
        System.out.println("move Vector: " + move);
        System.out.println("position Vector: " + positionVector);
       
        //Put camera onto its physics body.
        cam.setLocation(cameraPhysicsBody.getPhysicsLocation().clone());
       
        //reset position vector to reflect what the phsyics engine actually moved.
        positionVector = cameraPhysicsBody.getPhysicsLocation().clone();
       
**rotation was not effected by the new collision detection**
        //Rotation
        quat = new Quaternion();
        quat.fromAngleAxis(rotation, Vector3f.UNIT_Y);
        cam.setRotation(quat);
    }

No comments:

Post a Comment