Created
November 19, 2012 20:49
-
-
Save kjellski/4113782 to your computer and use it in GitHub Desktop.
Ray Collision Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
Geometry plane = new Geometry("quad", new Quad(size, size)); | |
Material planeMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); | |
planeMat.setColor("Color", ColorRGBA.Blue); | |
planeMat.getAdditionalRenderState().setWireframe(true); | |
plane.setMaterial(planeMat); | |
plane.center().move(pos); | |
rootNode.attachChild(plane); | |
... | |
private ActionListener shootActionListener = new ActionListener() { | |
public void onAction(String name, boolean keyPressed, float tpf) { | |
if (name.equals("Shoot") && !keyPressed) { | |
// 1. Reset results list. | |
CollisionResults results = new CollisionResults(); | |
// 2. Aim the ray from cam loc to cam direction. | |
Ray ray = new Ray(cam.getLocation(), cam.getDirection()); | |
// 3. Collect intersections between Ray and Shootables in results list. | |
rootNode.getChild("quad").collideWith(ray, results); | |
// 4. Print the results | |
System.out.println("----- Collisions: " + results.size() + "-----"); | |
for (int i = 0; i < results.size(); i++) { | |
// For each hit, we know distance, impact point, name of geometry. | |
float dist = results.getCollision(i).getDistance(); | |
Vector3f pt = results.getCollision(i).getContactPoint(); | |
String hit = results.getCollision(i).getGeometry().getName(); | |
System.out.println("* Collision #" + i); | |
System.out.println(" You shot " + hit + " at " + pt + ", " + dist + " wu away."); | |
} | |
// 5. Use the results (we mark the hit object) | |
if (results.size() > 0) { | |
// The closest collision point is what was truly hit: | |
CollisionResult closest = results.getClosestCollision(); | |
// Let's interact - we mark the hit with a red dot. | |
mark.setLocalTranslation(closest.getContactPoint()); | |
rootNode.attachChild(mark); | |
} else { | |
// No hits? Then remove the red mark. | |
rootNode.detachChild(mark); | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment