Skip to content

Commit d411fa3

Browse files
authored
Update Camera.java
1 parent c110698 commit d411fa3

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

jme3-core/src/main/java/com/jme3/renderer/Camera.java

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
import com.jme3.math.Matrix4f;
4343
import com.jme3.math.Plane;
4444
import com.jme3.math.Quaternion;
45+
import com.jme3.math.Ray;
4546
import com.jme3.math.Vector2f;
4647
import com.jme3.math.Vector3f;
4748
import com.jme3.math.Vector4f;
@@ -1570,6 +1571,40 @@ public Vector3f getScreenCoordinates(Vector3f worldPosition, Vector3f store) {
15701571
return store;
15711572
}
15721573

1574+
/**
1575+
* Returns a ray going from camera through a screen point.
1576+
* <p>
1577+
* Resulting ray is in world space, starting on the near plane
1578+
* of the camera and going through position's (x,y) pixel coordinates on the screen.
1579+
*
1580+
* @param click2d A {@link Vector2f} representing the 2D screen coordinates (in pixels)
1581+
* @return A {@link Ray} object representing the picking ray in world coordinates.
1582+
*
1583+
* <h3>Usage Example:</h3>
1584+
* <pre>{@code
1585+
* Ray pickingRay = cam.screenPointToRay(inputManager.getCursorPosition());
1586+
*
1587+
* // Now 'pickingRay' can be used for intersection tests with 3D objects
1588+
* // e.g., pickingRay.intersects(someSpatial.getWorldBound());
1589+
* }</pre>
1590+
*/
1591+
public Ray screenPointToRay(Vector2f click2d) {
1592+
TempVars vars = TempVars.get();
1593+
Vector3f nearPoint = vars.vect1;
1594+
Vector3f farPoint = vars.vect2;
1595+
1596+
// Get the world coordinates for the near and far points
1597+
getWorldCoordinates(click2d, 0, nearPoint);
1598+
getWorldCoordinates(click2d, 1, farPoint);
1599+
1600+
// Calculate direction and normalize
1601+
Vector3f direction = farPoint.subtractLocal(nearPoint).normalizeLocal();
1602+
1603+
Ray ray = new Ray(nearPoint, direction);
1604+
vars.release();
1605+
return ray;
1606+
}
1607+
15731608
/**
15741609
* Returns the display width.
15751610
*
@@ -1590,9 +1625,14 @@ public int getHeight() {
15901625

15911626
@Override
15921627
public String toString() {
1593-
return "Camera[location=" + location + "\n, direction=" + getDirection() + "\n"
1594-
+ "res=" + width + "x" + height + ", parallel=" + parallelProjection + "\n"
1595-
+ "near=" + frustumNear + ", far=" + frustumFar + "]";
1628+
return getClass().getSimpleName()
1629+
+ "[location=" + location
1630+
+ ", direction=" + getDirection()
1631+
+ ", res=" + width + "x" + height
1632+
+ ", parallel=" + parallelProjection
1633+
+ ", near=" + frustumNear
1634+
+ ", far=" + frustumFar
1635+
+ "]";
15961636
}
15971637

15981638
@Override

0 commit comments

Comments
 (0)