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


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

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
translate(boxCenter.x, boxCenter.y, boxCenter.z);

Here is a picture showing the principle :

Have fun! :wink:


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 :

Thanks guy !I wiil check soon!