com.badlogic.gdx.math.collision.Ray Java Examples

The following examples show how to use com.badlogic.gdx.math.collision.Ray. 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: BulletTargetInputProcessor.java    From gdx-ai with Apache License 2.0 6 votes vote down vote up
private btCollisionObject rayTest (Collision<Vector3> output, Ray ray) {
	rayFrom.set(ray.origin);
	// 500 meters max from the origin
	rayTo.set(ray.direction).scl(500f).add(rayFrom);

	// we reuse the ClosestRayResultCallback, thus we need to reset its
	// values
	callback.setCollisionObject(null);
	callback.setClosestHitFraction(1f);
	callback.setRayFromWorld(rayFrom);
	callback.setRayToWorld(rayTo);

	world.rayTest(rayFrom, rayTo, callback);

	if (callback.hasHit()) {
		callback.getHitPointWorld(output.point);
		callback.getHitNormalWorld(output.normal);
		return callback.getCollisionObject();
	}

	return null;
}
 
Example #2
Source File: ModelPlacementTool.java    From Mundus with Apache License 2.0 6 votes vote down vote up
@Override
public boolean mouseMoved(int screenX, int screenY) {
    if (this.model == null || modelInstance == null) return false;

    final ProjectContext context = getProjectManager().current();

    final Ray ray = getProjectManager().current().currScene.viewport.getPickRay(screenX, screenY);
    if (context.currScene.terrains.size > 0 && modelInstance != null) {
        MeshPartBuilder.VertexInfo vi = TerrainUtils.getRayIntersectionAndUp(context.currScene.terrains, ray);
        if (vi != null) {
            if (shouldRespectTerrainSlope) {
                modelInstance.transform.setToLookAt(DEFAULT_ORIENTATION, vi.normal);
            }
            modelInstance.transform.setTranslation(vi.position);
        }
    } else {
        tempV3.set(getProjectManager().current().currScene.cam.position);
        tempV3.add(ray.direction.nor().scl(200));
        modelInstance.transform.setTranslation(tempV3);
    }

    return false;
}
 
Example #3
Source File: GameEngine.java    From GdxDemo3D with Apache License 2.0 6 votes vote down vote up
public Entity rayTest(Ray ray, Vector3 hitPointWorld, short belongsToFlag, short collidesWithFlag,
					  float rayDistance, Bits layers) {
	rayFrom.set(ray.origin);
	rayTo.set(ray.direction).scl(rayDistance).add(rayFrom);
	callback.setCollisionObject(null);
	callback.setClosestHitFraction(1f);
	callback.setRay(ray, rayDistance);
	callback.setLayers(layers);

	callback.setCollisionFilterMask(belongsToFlag);
	callback.setCollisionFilterGroup(collidesWithFlag);

	dynamicsWorld.rayTest(rayFrom, rayTo, callback);

	if (callback.hasHit()) {
		if (hitPointWorld != null) {
			callback.getHitPointWorld(hitPointWorld);
		}
		long entityId = callback.getCollisionObject().getUserPointer();
		return getEntity(entityId);
	}
	return null;
}
 
Example #4
Source File: CameraController.java    From GdxDemo3D with Apache License 2.0 6 votes vote down vote up
public void processDragPan(Ray dragCurrentRay, Ray lastDragProcessedRay) {
	followTarget = null;
	// TODO:
	// Can probably be optimized, but simply storing worldDragLast.set(worldDragCurrent)
	// caused jitter for some reason.
	Intersector.intersectRayPlane(dragCurrentRay, worldGroundPlane, worldDragCurrent);
	Intersector.intersectRayPlane(lastDragProcessedRay, worldGroundPlane, worldDragLast);
	tmp1.set(worldDragLast).sub(worldDragCurrent);
	tmp1.y = 0;

	ray.origin.set(camera.targetPosition).add(tmp1);
	ray.direction.set(camera.targetDirection);
	if (Intersector.intersectRayBoundsFast(ray, worldBoundingBox)) {
		camera.targetPosition.add(tmp1);
		worldGroundTarget.add(tmp1);
	}
}
 
Example #5
Source File: NavMesh.java    From GdxDemo3D with Apache License 2.0 6 votes vote down vote up
/**
 * Get the triangle which this ray intersects. Returns null if no triangle is intersected.
 *
 * @param ray
 * @param distance
 * @param allowedMeshParts
 * @return
 */
public Triangle rayTest(Ray ray, float distance, Bits allowedMeshParts) {
	Triangle hitTriangle = null;

	tmpRayTestRayFrom.set(ray.origin);
	tmpRayTestRayTo.set(ray.direction).scl(distance).add(tmpRayTestRayFrom);
	raycastCallback.setHitFraction(1);
	raycastCallback.clearReport();
	raycastCallback.setFrom(tmpRayTestRayFrom);
	raycastCallback.setTo(tmpRayTestRayTo);
	raycastCallback.setAllowedMeshPartIndices(allowedMeshParts);
	collisionShape.performRaycast(raycastCallback, tmpRayTestRayFrom, tmpRayTestRayTo);

	if (raycastCallback.triangleIndex != -1) {
		hitTriangle = graph.getTriangleFromMeshPart(raycastCallback.partId, raycastCallback.triangleIndex);
	}
	return hitTriangle;
}
 
Example #6
Source File: Terrain.java    From Mundus with Apache License 2.0 6 votes vote down vote up
public Vector3 getRayIntersection(Vector3 out, Ray ray) {
    // TODO improve performance. use binary search
    float curDistance = 2;
    int rounds = 0;

    ray.getEndPoint(out, curDistance);
    boolean isUnder = isUnderTerrain(out);

    while (true) {
        rounds++;
        ray.getEndPoint(out, curDistance);

        boolean u = isUnderTerrain(out);
        if (u != isUnder || rounds == 10000) {
            return out;
        }
        curDistance += u ? -0.1f : 0.1f;
    }

}
 
Example #7
Source File: NavMesh.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate a triangle graph path between two triangles which are intersected by the rays.
 *
 * @param fromRay
 * @param toRay
 * @param allowedMeshParts
 * @param distance
 * @param path
 * @return
 */
public boolean getPath(Ray fromRay, Ray toRay, Bits allowedMeshParts,
					   float distance, NavMeshGraphPath path) {

	Triangle fromTri = rayTest(fromRay, distance, allowedMeshParts);
	if (fromTri == null) {
		Gdx.app.debug(TAG, "From triangle not found.");
		return false;
	}
	Vector3 fromPoint = new Vector3();
	Intersector.intersectRayTriangle(fromRay, fromTri.a, fromTri.b, fromTri.c, fromPoint);

	return getPath(fromTri, fromPoint, toRay, allowedMeshParts, distance, path);
}
 
Example #8
Source File: BulletTargetInputProcessor.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
private boolean setTargetPosition (int screenX, int screenY) {
	if (moveTarget) {
		Ray pickRay = viewport.getPickRay(screenX, screenY);
		btCollisionObject body = rayTest(output, pickRay);

		if (body != null && body.userData != null && body.userData.equals("ground")) {
			target.transform.setToTranslation(output.point.add(offset));
			target.body.setWorldTransform(target.transform);
		}
		return true;
	}
	return false;
}
 
Example #9
Source File: Stage3d.java    From Scene3d with Apache License 2.0 5 votes vote down vote up
public Actor3d hit3d(int screenX, int screenY, Actor3d actor3d) {
    Ray ray = camera.getPickRay(screenX, screenY);
    float distance = -1;
    final float dist2 = actor3d.intersects(ray);
    if (dist2 >= 0f && (distance < 0f || dist2 <= distance)) { 
        distance = dist2;
        return actor3d;
    }
    return null;
}
 
Example #10
Source File: Actor3d.java    From Scene3d with Apache License 2.0 5 votes vote down vote up
/** @return -1 on no intersection, or when there is an intersection: the squared distance between the center of this 
 * object and the point on the ray closest to this object when there is intersection. */
public float intersects(Ray ray) {
    transform.getTranslation(position).add(center);
    final float len = ray.direction.dot(position.x-ray.origin.x, position.y-ray.origin.y, position.z-ray.origin.z);
    if (len < 0f)
        return -1f;
    float dist2 = position.dst2(ray.origin.x+ray.direction.x*len, ray.origin.y+ray.direction.y*len, ray.origin.z+ray.direction.z*len);
    return (dist2 <= radius * radius) ? dist2 : -1f;
}
 
Example #11
Source File: Stage3D.java    From gdx-vr with Apache License 2.0 5 votes vote down vote up
@Override
public Vector2 screenToStageCoordinates(Vector2 screenCoords) {
	Ray pickRay = getViewport().getPickRay(screenCoords.x, screenCoords.y);
	Vector3 intersection = tmp;
	if (Intersector.intersectRayPlane(pickRay, plane, intersection)) {
		screenCoords.x = intersection.x;
		screenCoords.y = intersection.y;
	} else {
		screenCoords.x = Float.MAX_VALUE;
		screenCoords.y = Float.MAX_VALUE;
	}
	return screenCoords;
}
 
Example #12
Source File: NavMesh.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate a triangle graph path from a start triangle to the triangle which is intersected by a ray.
 *
 * @param fromTri
 * @param fromPoint
 * @param toRay
 * @param allowedMeshParts
 * @param distance
 * @param path
 * @return
 */
public boolean getPath(Triangle fromTri, Vector3 fromPoint, Ray toRay, Bits allowedMeshParts,
					   float distance, NavMeshGraphPath path) {
	Triangle toTri = rayTest(toRay, distance, allowedMeshParts);
	if (toTri == null) {
		Gdx.app.debug(TAG, "To triangle not found.");
		return false;
	}
	Vector3 toPoint = new Vector3();
	Intersector.intersectRayTriangle(toRay, toTri.a, toTri.b, toTri.c, toPoint);

	return getPath(fromTri, fromPoint, toTri, toPoint, path);
}
 
Example #13
Source File: FollowPathSteerer.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
public boolean calculateNewPath(Ray ray, Bits visibleLayers) {
	if (GameScreen.screen.engine.getScene().navMesh.getPath(
			steerableBody.getCurrentTriangle(),
			steerableBody.getGroundPosition(tmpVec1),
			ray, visibleLayers,
			GameSettings.CAMERA_PICK_RAY_DST,
			navMeshGraphPath)) {

		calculateNewPath0();
		return true;
	}
	return false;
}
 
Example #14
Source File: HumanCharacter.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
@Override
public void handleMovementRequest(Ray ray, Bits visibleLayers) {
	// A man only moves if is idle or already moving
	// For instance, the movement request will be ignored if the man is throwing the stick
	HumanState state = stateMachine.getCurrentState();
	if (state.isIdleState() || state.isMovementState()) {
		followPathSteerer.calculateNewPath(ray, visibleLayers);
	}
}
 
Example #15
Source File: GameEngine.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
public void setRay(Ray ray, float rayDistance) {
	this.ray.set(ray);
	this.rayDistance = rayDistance;
	rayFrom.set(ray.origin);
	rayTo.set(ray.direction).scl(rayDistance).add(rayFrom);
	setRayFromWorld(rayFrom);
	setRayToWorld(rayTo);
}
 
Example #16
Source File: TerrainBrush.java    From Mundus with Apache License 2.0 5 votes vote down vote up
@Override
public boolean mouseMoved(int screenX, int screenY) {
    if (terrainAsset != null) {
        Ray ray = getProjectManager().current().currScene.viewport.getPickRay(screenX, screenY);
        terrainAsset.getTerrain().getRayIntersection(brushPos, ray);
    }

    mouseMoved = true;

    Shaders.INSTANCE.getTerrainShader().setPickerPosition(brushPos.x, brushPos.y, brushPos.z);

    return false;
}
 
Example #17
Source File: GameStage.java    From GdxDemo3D with Apache License 2.0 4 votes vote down vote up
public void handleMovementRequest(Ray ray, Bits visibleLayers) {
	// Handle movement request only if a character is selected and a movement button is checked
	if (selectedCharacter != null && radioGroup.getCheckedIndex() > -1 && radioGroup.getChecked().state.isMovementState()) {
		selectedCharacter.handleMovementRequest(ray, visibleLayers);
	}
}
 
Example #18
Source File: NavMeshPointPath.java    From GdxDemo3D with Apache License 2.0 4 votes vote down vote up
/**
 * Calculate the shortest path through the navigation mesh triangles.
 *
 * @param trianglePath
 */
public void calculateForGraphPath(NavMeshGraphPath trianglePath) {
	clear();
	nodes = trianglePath.nodes;
	this.start = new Vector3(trianglePath.start);
	this.end = new Vector3(trianglePath.end);
	this.startTri = trianglePath.startTri;

	// Check that the start point is actually inside the start triangle, if not, project it to the closest
	// triangle edge. Otherwise the funnel calculation might generate spurious path segments.
	Ray ray = new Ray(tmp1.set(V3_UP).scl(1000).add(start), tmp2.set(V3_DOWN));
	if (!Intersector.intersectRayTriangle(ray, startTri.a, startTri.b, startTri.c, null)) {
		float minDst = Float.POSITIVE_INFINITY;
		Vector3 projection = new Vector3();
		Vector3 newStart = new Vector3();
		float dst;
		// A-B
		if ((dst = GeometryUtils.nearestSegmentPointSquareDistance(projection, startTri.a, startTri.b, start)) < minDst) {
			minDst = dst;
			newStart.set(projection);
		}
		// B-C
		if ((dst = GeometryUtils.nearestSegmentPointSquareDistance(projection, startTri.b, startTri.c, start)) < minDst) {
			minDst = dst;
			newStart.set(projection);
		}
		// C-A
		if ((dst = GeometryUtils.nearestSegmentPointSquareDistance(projection, startTri.c, startTri.a, start)) < minDst) {
			minDst = dst;
			newStart.set(projection);
		}
		start.set(newStart);
	}
	if (nodes.size == 0) {
		addPoint(start, startTri);
		addPoint(end, startTri);
	} else {
		lastEdge = new Edge(nodes.get(nodes.size - 1).getToNode(), nodes.get(nodes.size - 1).getToNode(), end, end);
		calculateEdgePoints();
	}
}
 
Example #19
Source File: CameraController.java    From GdxDemo3D with Apache License 2.0 4 votes vote down vote up
public void processTouchDownLeft(Ray ray) {
	Intersector.intersectRayPlane(ray, worldGroundPlane, worldDragCurrent);
	worldDragLast.set(worldDragCurrent);
}
 
Example #20
Source File: VirtualScreenViewport.java    From libgdx-snippets with MIT License 4 votes vote down vote up
@Override
public Ray getPickRay(float screenX, float screenY) {
	return getPickRay(screenX, screenY, 0, 0, getScreenWidth(), getScreenHeight());
}
 
Example #21
Source File: SplitViewport.java    From gdx-vr with Apache License 2.0 4 votes vote down vote up
@Override
public Ray getPickRay(float screenX, float screenY) {
	return rootViewport.getPickRay(screenX, screenY);
}
 
Example #22
Source File: GameObject.java    From GdxDemo3D with Apache License 2.0 4 votes vote down vote up
public void handleMovementRequest(Ray ray, Bits visibleLayers) {
}
 
Example #23
Source File: TranslateTool.java    From Mundus with Apache License 2.0 4 votes vote down vote up
@Override
public void act() {
    super.act();

    if (getProjectManager().current().currScene.currentSelection != null) {
        translateHandles();
        if (state == TransformState.IDLE) return;

        Ray ray = getProjectManager().current().currScene.viewport.getPickRay(Gdx.input.getX(), Gdx.input.getY());
        Vector3 rayEnd = getProjectManager().current().currScene.currentSelection.getLocalPosition(temp0);
        float dst = getProjectManager().current().currScene.cam.position.dst(rayEnd);
        rayEnd = ray.getEndPoint(rayEnd, dst);

        if (initTranslate) {
            initTranslate = false;
            lastPos.set(rayEnd);
        }

        GameObject go = getProjectManager().current().currScene.currentSelection;

        boolean modified = false;
        Vector3 vec = new Vector3();
        if (state == TransformState.TRANSFORM_XZ) {
            vec.set(rayEnd.x - lastPos.x, 0, rayEnd.z - lastPos.z);
            modified = true;
        } else if (state == TransformState.TRANSFORM_X) {
            vec.set(rayEnd.x - lastPos.x, 0, 0);
            modified = true;
        } else if (state == TransformState.TRANSFORM_Y) {
            vec.set(0, rayEnd.y - lastPos.y, 0);
            modified = true;
        } else if (state == TransformState.TRANSFORM_Z) {
            vec.set(0, 0, rayEnd.z - lastPos.z);
            modified = true;
        }

        // TODO translation in global sapce
        // if(globalSpace) {
        // System.out.println("Before: " + vec);
        // System.out.println("After: " + vec);
        // }

        go.translate(vec);

        if (modified) {
            gameObjectModifiedEvent.setGameObject(getProjectManager().current().currScene.currentSelection);
            Mundus.INSTANCE.postEvent(gameObjectModifiedEvent);
        }

        lastPos.set(rayEnd);
    }
}