Hello. I’m trying to create a third person controller by myself for training purposes. Everything has gone well so far, but i’m stuck at making the camera follow the player at a certain distance (5 units), no matter it’s orientation around the player. I know there are a couple of other threads, which I have read. But either they are not explanatory enough, or don’t solve my problem.
I know I can get the distance from the camera to the character by subtracting the camera’s position from the player’s position and getting the magnitude from that Vector3. However, I do not know how to apply this distance to the camera’s position, since I assume that you can’t add a float to a Vector3.
A detailed explanation of how to solve this would be greatly appreciated.
Thanks
Alex
I would say try thinking your method in reverse. Instead of trying to find the distance from the camera to the player object and then applying that. You already know what distance you want, and I assume you know what position around the player you want your camera to be positioned at. So you should think about positioning the camera based on the player’s location.
//Distance away from player you want to be at.
var distance = 10.0f;
//Direction from the player you want to be at.
//Use a unit vector which can be found from any Vector3 using .Normalize
//This vector is pointing behind and above the player at a 45deg angle
var direction = new Vector3(-10, 10, 0);
//distance * direction. normalized(); scales the unit vector to a constant size of distance behind the player.
camera.position = player.position + distance * direction. normalized();
get the slope of the line of the from the player to the camera
normalize
multiply by 5
assign that to the camera
that’d be done as
camera.transform.position = (camera.transform.position - player.transform.position).normalized * 5;
or
get the slope of the line from player to player to the camera
use that as a ray so you have origin and direction
get the point 5 units along the ray
ray.point(5)
assign that to the camera
mark as answered please
You could use the very useful Mathf.Clamp method on the camera’s transform. For instance, when moving the camera you would “clamp” its position to always be at your specified distance (e.g. 5 units in your example). Mathf.Clamp in the Scripting Reference