So, I’m trying to do ray-casting for hit detection in my shooter, but the ray always seems to be off from the coordinates I’m sending it. I cant for the life of me figure out where I’m making an error, other than that it could have something to do with the camera angle.
Below I have pasted in the code for my shoot() method, I’m also drawing a line for testing that should show where the ray is, but the mark that shows up on the targets is always some small angle off from where the line shows.
[java]
private void shoot(){
//BUG: Ray does not line up perfectly with line
CollisionResults results = new CollisionResults();
Vector2f mousePosNoOff = new Vector2f();
//Converts from screen position to a coord grid of -1.0 to +1.0
mousePosNoOff.x = (cursorPos.x - settings.getWidth()/2)/(settings.getWidth()/2);
mousePosNoOff.y = (cursorPos.y - settings.getHeight()/2)/(settings.getHeight()/2);
//Convert to polar coords so I can add 45 degrees
float polarAngle = mousePosNoOff.getAngle() - FastMath.PI/4;
float polarMag = FastMath.sqrt(FastMath.pow(mousePosNoOff.x, 2) + FastMath.pow(mousePosNoOff.y, 2));
Vector2f mousePos = new Vector2f(polarMag * FastMath.cos(polarAngle),
polarMag * FastMath.sin(polarAngle));
Vector3f playerPos = player.getWorldPos();
Vector3f rayCoords = new Vector3f(((mousePos.x * 300) + playerPos.x),
((mousePos.y * 300) + playerPos.y),
1f);
Ray ray = new Ray(playerPos, rayCoords);
System.out.println(ray);
//Line that I’m using for testing - it should have the same coords as ray
Mesh lineMesh = new Mesh();
lineMesh.setMode(Mesh.Mode.Lines);
lineMesh.setLineWidth(5f);
lineMesh.setBuffer(VertexBuffer.Type.Position, 3, new float[]{
playerPos.x,
playerPos.y,
playerPos.z,
rayCoords.x,
rayCoords.y,
rayCoords.z
});
lineMesh.setBuffer(VertexBuffer.Type.Index, 2, new short[]{ 0, 1 });
lineMesh.updateBound();
lineMesh.updateCounts();
line.setMesh(lineMesh);
shootables.collideWith(ray, results);
if (results.size() > 0) {
System.out.println("
Collisions? " + results.size() + "
");
float dist = results.getClosestCollision().getDistance();
Vector3f pt = results.getClosestCollision().getContactPoint();
String hit = results.getClosestCollision().getGeometry().getName();
System.out.println(" You shot " + hit + " at " + pt + ", " + dist + " wu away.");
if(pt != null){
mark.setLocalTranslation(pt);
rootNode.attachChild(mark);
System.out.println(mark.getLocalTranslation());
}
} else {
rootNode.detachChild(mark);
}
}
[/java]
What am I doing wrong? Why is the ray not lined up with the line?
If anyone needs more info, the full source is here: https://github.com/ildrean/TerraNullius/blob/master/com/Game.java