Java Code Examples for com.jme3.collision.CollisionResults#getClosestCollision()

The following examples show how to use com.jme3.collision.CollisionResults#getClosestCollision() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TerrainQuad.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Gather the terrain patches that intersect the given ray (toTest).
 * This only tests the bounding boxes
 * @param toTest
 * @param results
 */
public void findPick(Ray toTest, List<TerrainPickData> results) {

    if (getWorldBound() != null) {
        if (getWorldBound().intersects(toTest)) {
            // further checking needed.
            for (int i = 0; i < getQuantity(); i++) {
                if (children.get(i) instanceof TerrainPatch) {
                    TerrainPatch tp = (TerrainPatch) children.get(i);
                    tp.ensurePositiveVolumeBBox();
                    if (tp.getWorldBound().intersects(toTest)) {
                        CollisionResults cr = new CollisionResults();
                        toTest.collideWith(tp.getWorldBound(), cr);
                        if (cr.getClosestCollision() != null) {
                            cr.getClosestCollision().getDistance();
                            results.add(new TerrainPickData(tp, cr.getClosestCollision()));
                        }
                    }
                }
                else if (children.get(i) instanceof TerrainQuad) {
                    ((TerrainQuad) children.get(i)).findPick(toTest, results);
                }
            }
        }
    }
}
 
Example 2
Source File: TestObjGroupsLoading.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void simpleUpdate(final float tpf) {
    
    // ray to the center of the screen from the camera
    Ray ray = new Ray(cam.getLocation(), cam.getDirection());
    
    // find object at the center of the screen

    final CollisionResults results = new CollisionResults();
    rootNode.collideWith(ray, results);
    
    CollisionResult result = results.getClosestCollision();
    if (result == null) {
        pointerDisplay.setText("");
    } else {
        // display pointed geometry and it's parents names
        StringBuilder sb = new StringBuilder();
        for (Spatial node = result.getGeometry(); node != null; node = node.getParent()) {
            if (sb.length() > 0) {
                sb.append(" < ");
            }
            sb.append(node.getName());
        }
        pointerDisplay.setText(sb);
    }
}
 
Example 3
Source File: TerrainQuad.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Gather the terrain patches that intersect the given ray (toTest).
 * This only tests the bounding boxes
 * @param toTest
 * @param results
 */
public void findPick(Ray toTest, List<TerrainPickData> results) {

    if (getWorldBound() != null) {
        if (getWorldBound().intersects(toTest)) {
            // further checking needed.
            for (int i = 0; i < getQuantity(); i++) {
                if (children.get(i) instanceof TerrainPatch) {
                    TerrainPatch tp = (TerrainPatch) children.get(i);
                    tp.ensurePositiveVolumeBBox();
                    if (tp.getWorldBound().intersects(toTest)) {
                        CollisionResults cr = new CollisionResults();
                        toTest.collideWith(tp.getWorldBound(), cr);
                        if (cr != null && cr.getClosestCollision() != null) {
                            cr.getClosestCollision().getDistance();
                            results.add(new TerrainPickData(tp, cr.getClosestCollision()));
                        }
                    }
                }
                else if (children.get(i) instanceof TerrainQuad) {
                    ((TerrainQuad) children.get(i)).findPick(toTest, results);
                }
            }
        }
    }
}
 
Example 4
Source File: TerrainCameraController.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Find where on the terrain the mouse intersects.
 */
protected Vector3f getTerrainCollisionPoint() {

    if (editorController.getTerrain(null) == null) {
        return null;
    }

    CollisionResults results = new CollisionResults();
    Ray ray = new Ray();
    Vector3f pos = cam.getWorldCoordinates(new Vector2f(mouseX, mouseY), 0).clone();
    Vector3f dir = cam.getWorldCoordinates(new Vector2f(mouseX, mouseY), 0.3f).clone();
    dir.subtractLocal(pos).normalizeLocal();
    ray.setOrigin(pos);
    ray.setDirection(dir);
    editorController.getTerrain(null).collideWith(ray, results);
    if (results == null) {
        return null;
    }
    final CollisionResult result = results.getClosestCollision();
    if (result == null) {
        return null;
    }
    return result.getContactPoint();
}
 
Example 5
Source File: TestMousePick.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
    public void simpleUpdate(float tpf){
        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();
        shootables.collideWith(ray, 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).getWorldContactPoint();
//            String hit = results.getCollision(i).getGeometry().getName();
//            System.out.println("* Collision #" + i);
//            System.out.println("  You shot " + hit + " at " + pt + ", " + dist + " wu away.");
//        }
        if (results.size() > 0) {
            CollisionResult closest = results.getClosestCollision();
            mark.setLocalTranslation(closest.getContactPoint());

            Quaternion q = new Quaternion();
            q.lookAt(closest.getContactNormal(), Vector3f.UNIT_Y);
            mark.setLocalRotation(q);

            rootNode.attachChild(mark);
        } else {
            rootNode.detachChild(mark);
        }
    }
 
Example 6
Source File: TerrainTestModifyHeight.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Vector3f getWorldIntersection() {
    Vector3f origin = cam.getWorldCoordinates(new Vector2f(settings.getWidth() / 2, settings.getHeight() / 2), 0.0f);
    Vector3f direction = cam.getWorldCoordinates(new Vector2f(settings.getWidth() / 2, settings.getHeight() / 2), 0.3f);
    direction.subtractLocal(origin).normalizeLocal();

    Ray ray = new Ray(origin, direction);
    CollisionResults results = new CollisionResults();
    int numCollisions = terrain.collideWith(ray, results);
    if (numCollisions > 0) {
        CollisionResult hit = results.getClosestCollision();
        return hit.getContactPoint();
    }
    return null;
}
 
Example 7
Source File: HelloPicking.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
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.
    shootables.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);
    }
  }
}
 
Example 8
Source File: TestDepthOfField.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void simpleUpdate(float tpf) {
    Vector3f origin = cam.getWorldCoordinates(new Vector2f(settings.getWidth() / 2, settings.getHeight() / 2), 0.0f);
    Vector3f direction = cam.getWorldCoordinates(new Vector2f(settings.getWidth() / 2, settings.getHeight() / 2), 0.3f);
    direction.subtractLocal(origin).normalizeLocal();
    Ray ray = new Ray(origin, direction);
    CollisionResults results = new CollisionResults();
    int numCollisions = terrain.collideWith(ray, results);
    if (numCollisions > 0) {
        CollisionResult hit = results.getClosestCollision();
        fpsText.setText(""+hit.getDistance());
        dofFilter.setFocusDistance(hit.getDistance()/10.0f);
    }
}
 
Example 9
Source File: PointUtil.java    From OpenRTS with MIT License 5 votes vote down vote up
private static CollisionResult getCollision(Node n, Ray r) {
	CollisionResults results = new CollisionResults();
	n.collideWith(r, results);
	if (results.size() == 0) {
		return null;
	}
	return results.getClosestCollision();
}
 
Example 10
Source File: TestMousePick.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
    public void simpleUpdate(float tpf){
        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();
        shootables.collideWith(ray, 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).getWorldContactPoint();
//            String hit = results.getCollision(i).getGeometry().getName();
//            System.out.println("* Collision #" + i);
//            System.out.println("  You shot " + hit + " at " + pt + ", " + dist + " wu away.");
//        }
        if (results.size() > 0) {
            CollisionResult closest = results.getClosestCollision();
            mark.setLocalTranslation(closest.getContactPoint());

            Quaternion q = new Quaternion();
            q.lookAt(closest.getContactNormal(), Vector3f.UNIT_Y);
            mark.setLocalRotation(q);

            rootNode.attachChild(mark);
        } else {
            rootNode.detachChild(mark);
        }
    }
 
Example 11
Source File: TerrainTestModifyHeight.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Vector3f getWorldIntersection() {
    Vector3f origin = cam.getWorldCoordinates(new Vector2f(settings.getWidth() / 2, settings.getHeight() / 2), 0.0f);
    Vector3f direction = cam.getWorldCoordinates(new Vector2f(settings.getWidth() / 2, settings.getHeight() / 2), 0.3f);
    direction.subtractLocal(origin).normalizeLocal();

    Ray ray = new Ray(origin, direction);
    CollisionResults results = new CollisionResults();
    int numCollisions = terrain.collideWith(ray, results);
    if (numCollisions > 0) {
        CollisionResult hit = results.getClosestCollision();
        return hit.getContactPoint();
    }
    return null;
}
 
Example 12
Source File: HelloPicking.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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.
    shootables.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);
    }
  }
}
 
Example 13
Source File: TestDepthOfField.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void simpleUpdate(float tpf) {
    Vector3f origin = cam.getWorldCoordinates(new Vector2f(settings.getWidth() / 2, settings.getHeight() / 2), 0.0f);
    Vector3f direction = cam.getWorldCoordinates(new Vector2f(settings.getWidth() / 2, settings.getHeight() / 2), 0.3f);
    direction.subtractLocal(origin).normalizeLocal();
    Ray ray = new Ray(origin, direction);
    CollisionResults results = new CollisionResults();
    int numCollisions = terrain.collideWith(ray, results);
    if (numCollisions > 0) {
        CollisionResult hit = results.getClosestCollision();
        fpsText.setText(""+hit.getDistance());
        dofFilter.setFocusDistance(hit.getDistance()/10.0f);
    }
}
 
Example 14
Source File: SceneEditTool.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private CollisionResult pick(Camera cam, Vector2f mouseLoc, Node node) {
    CollisionResults results = new CollisionResults();
    Ray ray = new Ray();
    Vector3f pos = cam.getWorldCoordinates(mouseLoc, 0).clone();
    Vector3f dir = cam.getWorldCoordinates(mouseLoc, 0.1f).clone();
    dir.subtractLocal(pos).normalizeLocal();
    ray.setOrigin(pos);
    ray.setDirection(dir);
    node.collideWith(ray, results);
    CollisionResult result = results.getClosestCollision();
    return result;
}
 
Example 15
Source File: MoveToolControl.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
@Override
@JmeThread
public void processTransform() {

    final EditorTransformSupport editorControl = getEditorControl();
    final LocalObjects local = LocalObjects.get();

    final Camera camera = editorControl.getCamera();
    final InputManager inputManager = EditorUtil.getInputManager();
    final Vector2f cursorPosition = inputManager.getCursorPosition();
    final CollisionResults results = local.nextCollisionResults();

    final Vector3f position = camera.getWorldCoordinates(cursorPosition, 0f, local.nextVector());
    final Vector3f direction = camera.getWorldCoordinates(cursorPosition, 1f, local.nextVector())
            .subtractLocal(position)
            .normalizeLocal();

    final Ray ray = local.nextRay();
    ray.setOrigin(position);
    ray.setDirection(direction);

    final Node collisionPlane = getCollisionPlane();
    collisionPlane.collideWith(ray, results);

    final CollisionResult result = results.getClosestCollision();
    final Transform transform = editorControl.getTransformCenter();

    // Complex trigonometry formula based on sin(angle)*distance
    if (result == null || transform == null) {
        return;
    }

    final Node parentNode = getParentNode();

    final Vector3f translation = parentNode.getLocalTranslation();
    final Vector3f contactPoint = result.getContactPoint(); // get a point of collisionPlane

    //set new deltaVector if it's not set
    if (Float.isNaN(editorControl.getTransformDeltaX())) {
        editorControl.setTransformDeltaX(translation.getX() - contactPoint.getX());
        editorControl.setTransformDeltaY(translation.getY() - contactPoint.getY());
        editorControl.setTransformDeltaZ(translation.getZ() - contactPoint.getZ());
    }

    // add delta of the picked place
    contactPoint.addLocal(editorControl.getTransformDeltaX(), editorControl.getTransformDeltaY(),
            editorControl.getTransformDeltaZ());

    final Vector3f difference = contactPoint.subtract(translation, local.nextVector());
    float distanceToContactPoint = translation.distance(contactPoint);

    // Picked vector
    final PickedAxis pickedAxis = editorControl.getPickedAxis();
    final TransformationMode transformationMode = editorControl.getTransformationMode();
    final Vector3f pickedVector = transformationMode.getPickedVector(transform, pickedAxis, camera);
    final Quaternion rotation = parentNode.getLocalRotation();

    // the main formula for constraint axis
    final Vector3f normalizedDifference = local.nextVector(difference).normalizeLocal();

    float angle = normalizedDifference.angleBetween(rotation.mult(pickedVector, local.nextVector())
            .normalizeLocal());

    float distanceVec2 = distanceToContactPoint * FastMath.sin(angle);

    // fix if angle>90 degrees
    Vector3f perpendicularVec = collisionPlane.getLocalRotation()
            .mult(Vector3f.UNIT_X, local.nextVector())
            .multLocal(distanceVec2);

    Vector3f checkVec = contactPoint.add(perpendicularVec, local.nextVector())
            .subtractLocal(contactPoint)
            .normalizeLocal();

    float angleCheck = checkVec.angleBetween(normalizedDifference);

    if (angleCheck < FastMath.HALF_PI) {
        perpendicularVec.negateLocal();
    }

    // find distance to move
    float distanceToMove = contactPoint.addLocal(perpendicularVec).distance(translation);

    // invert value if it's needed for negative movement
    if (angle > FastMath.HALF_PI) {
        distanceToMove = -distanceToMove;
    }

    translateObjects(pickedAxis, notNull(editorControl.getToTransform()), transform, distanceToMove);
}
 
Example 16
Source File: AbstractSceneEditor3DPart.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
/**
 * Update editing nodes.
 */
@JmeThread
private void updatePaintingNodes() {

    if (!isPaintingMode()) {
        return;
    }

    final Node cursorNode = getCursorNode();
    final PaintingControl control = PaintingUtils.getPaintingControl(cursorNode);
    final Spatial paintedModel = PaintingUtils.getPaintedModel(control);
    if (paintedModel == null) {
        return;
    }

    final CollisionResults collisions = GeomUtils.getCollisionsFromCursor(paintedModel, getCamera());
    if (collisions.size() < 1) {
        return;
    }

    CollisionResult result = null;

    for (final CollisionResult collision : collisions) {

        final Geometry geometry = collision.getGeometry();
        final Object parent = NodeUtils.findParent(geometry, spatial ->
                spatial.getUserData(KEY_IGNORE_RAY_CAST) == Boolean.TRUE);

        if (parent == null) {
            result = collision;
            break;
        }
    }

    if (result == null) {
        result = collisions.getClosestCollision();
    }

    final Vector3f contactPoint = result.getContactPoint();
    final Vector3f contactNormal = result.getContactNormal();

    final LocalObjects local = LocalObjects.get();
    final Quaternion rotation = local.nextRotation();
    rotation.lookAt(contactNormal, Vector3f.UNIT_Y);

    cursorNode.setLocalRotation(rotation);
    cursorNode.setLocalTranslation(contactPoint);
}