How to get the position of the point directly in front of the camera?

Hello everyone! I want to put a box in front of a mobile camera, but no matter how I try, I can’t get it

Hi,

If you use the lookAt() function to point the camera at a certain point in space and the setPosition() function to set the location of the camera, you should be able to have the camera direction vector :

const cam = createCamera();
const cameraLocation = createVector(1, 1, 1);
const cameraLookAtPoint = createVector(0, 0, 0);

// Set the camera (order is important
cam.setPosition(cameraLocation);
cam.lookAt(cameraLocation);

Then compute the direction vector :

const cameraDirectionVector = p5.Vector.sub(cameraLookAtPoint, cameraLocation).normalize();

Then you can get any point on the direction of the camera by multiplying by a certain value :

const distanceFromCamera = 2;
const boxCenter = p5.Vector.add(cameraLocation, p5.Vector.mult(cameraDirectionVector, distanceFromCamera));

Then do the display part :

// Display the box
push();
translate(boxCenter.x, boxCenter.y, boxCenter.z);
box(0.5);
pop();

Here is a picture showing the principle :

Have fun! :wink:

3 Likes

Thank you so much! Solved a big problem for me! By the way, is it easy to convert the mouse to space position coordinates in p5, such as hitting a model like a bullet and getting their intersection point?

1 Like

very interesting.

Would that be possible in processing too?

You are welcome! :wink:

For mouse / geometry intersection, you need to cast a ray from the camera based on the field of view of the camera and the compute the intersection with the object.

Obviously it’s easier with a plane or a primitive shape since the intersection formulae is simple.

You can check this :

https://antongerdelan.net/opengl/raycasting.html

Thanks guy !I wiil check soon!