Hi guys,
I am working on a small tower defends game. I need to let player can select where they want to build the tower. Here is the code I create calculate the cursor position and attach the tower at it:
Vector3f origin = cam.getWorldCoordinates(inputManager.getCursorPosition(),0.0f);
Vector3f direction = cam.getWorldCoordinates(inputManager.getCursorPosition(),0.3f);
direction.subtractLocal(origin).normalizeLocal();
Ray ray = new Ray(origin,direction);
CollisionResults results = new CollisionResults();
rootNode.collideWith(ray, results);
if(results.size() > 0) {
CollisionResult closest = results.getClosestCollision();
mark.setLocalTranslation(closest.getContactPoint());
Quaternion q = new Quaternion();
q.lookAt(closest.getContactNormal(), Vector3f.UNIT_Z);
mark.setLocalRotation(q);
}
Here is the code that attach tower to the cursor position when player click mouse:
@Override
public void onAnalog(String name, float value,float tpf) {
if(name.equals("build")) {
float x = mark.getLocalTranslation().x;
float y = mark.getLocalTranslation().y;
float z = mark.getLocalTranslation().z;
geomTow.setLocalTranslation(x, y, z);
System.out.println("x: "+x+"\ny: "+y+"\nz: "+z);
}
}
But the results show the cube(tower) always move in front of the camera:
I also use the System.out.println(); method to print out the cursor location, here is the results:
x: 0.66858315
y: 0.0
z: 8.816481
x: 0.7650244
y: 0.69080544
z: 7.8164825
And I realized that the cursor position always change when attach the cube to the cursor and don’t change when I disable this:
geomTow.setLocalTranslation(mark.getLocalTranslation());
So the question is:
Does anything wrong there ? How to fix that ?