Hey!
I have a camera object and a player. I made the camera follow the player, but now I also want that the Y rotation of the camera is the same as the player. How can I make that?
Hey!
I have a camera object and a player. I made the camera follow the player, but now I also want that the Y rotation of the camera is the same as the player. How can I make that?
What do you mean? Did you link the camera to the player?
No because it is a sphere. I move the sphere with the keys and i want, that the camera is pointing at the direction i am moving in
If you want the camera to look at the player… use this code:
var target : Transform;
function Update () {
var relativePos = target.position - transform.position;
var rotation = Quaternion.LookRotation(relativePos);
transform.rotation = rotation;
}
More info on the LookRotation here: Unity - Scripting API: Quaternion.LookRotation
Let me give you a better solution.
var target : Transform;
var smooth : boolean = true;
var smoothSpeed : float = 2;
function LateUpdate(){
if(transform.position != target.position) return;
var position : Vector3 = transform.position;
position.y = target.position.y;
transform.position = position;
// set rotation
if(smooth){
var rotation : Quaternion = transform.rotation;
transform.LookAt(target);
transform.rotation = Quaternion.Lerp(transform.rotation, rotation, smoothSpeed * Time.deltaTime);
} else{
transform.LookAt(target);
}
// set position
transform.position = target.position;
}
The script sets the game object to basically the same position as the ball. It also “follows” the direction of the ball, either smooth or not.
This is done because the rotation of the game object only changes on the Y axis. (due to setting the Y position to the target’s Y position) Once you have it on the same plane, it never looks down or up, but always the same direction. you just rotate the camera around that point.
I could get a bit more advanced and make it one script that does everything for you, you just feed it a target and an offset, but you get the picture.