I have a problem : I need to know what is the position, in world coordinates, that the camera is pointing at. I don’t really know how to do it, I’ve seen such things as ScreenToWorldPoint(), but I don’t know how to use it (Why a Vector3 for input ? If we are talking about a screen, shouldn’t it be a Vector2 ?)
I’m thinking about Raycast and stuff but I’m really not familiar with these…
To be simple : how can I get a world position from the center of the screen ?
You are trying to get a point in a 3D ‘world’. The screen is 2D. Therefore, it is effectively looking along a given vector. So any point on the screen extends, in theory, along an infinite number of 3D points along that line.
If you want a world co-ordinate you have to pick a point ‘x’ distance from the camera to know at which point, in the 3D world space along that line, you wish to know the point of.
The documentation shows how to take the 3D point at the near clip plane of the main camera view.
This should theoretically return me the 3D point I’m looking at ? Because when I Debug.Log it, The coordinates does not change much when I’m looking near me/far from me… I am probably missing something but I don’t understand… It seems that the coordinates returned are always close to me, as they go higher when I’m displacing the camera.
Hey, I know this is very late, but I have a alternative solution for this.
var ray = Camera.main.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));
Vector3 lookAt = ray.direction*500f + barrel.position;
barrel.LookAt(lookAt);
The lookAt point is created by finding the direction the camera is facing, increasing that unit Vector by a very large amount and then moving it to the position of the barrel.
This comes from the equation for lines in R3: point on line = anchor point + direction unit vector * distance from anchor
An intriguing alternative, but I don’t really get it
OP wants to
With your code:
The tank is at (1,0,1). Camera is at (0,10,0), and looks in northeast direction but very downwards, to (-1,0,1).
The ray would thus have a direction of (-1,-10,1). lookAt = (-499,-5000,501), so LookAt looks in direction (-1,-10,1) (just as when lookAt would simply be (0,-10,2)), which is also northeast and very downwards.
But we want the tank to face (-1,0,1), aka a direction of (-1,0,0), west.