- Home /
Top-Down Camera: Always looking where the player is facing?
I use this code, which I did not write, to move the camera so it's always looking at the player, top-down 3rd person, as they move around the world. I'd like to adjust it so that when the player turns left or right, the camera moves around as well, so that the camera is always facing the same direction as the player.
[I've tried making the camera a child of the player object, but the result is a choppiness as the camera moves right/left with player but then gets pushed back, probably via the code]
How might I adjust this code to get the desired effect? I'm all for doing the research myself, if someone wants to point me in the right direction :)
using UnityEngine;
using System.Collections;
public class AttachCamera : MonoBehaviour
{
Transform myTransform;
public Transform target;
public Vector3 offset = new Vector3(0, 5, -5);
void Start()
{
myTransform = this.transform;
}
void FixedUpdate()
{
if (target != null)
{
myTransform.position = target.position + offset;
myTransform.LookAt(target.position, Vector3.up);
}
}
}
Answer by whebert · Jun 18, 2013 at 12:06 AM
If you want to try the parented approach:
void Start()
{
transform.parent = target;
transform.localPosition = offset;
transform.LookAt(target);
}
If not:
void Update()
{
myTransform.position = target.position + target.TransformDirection(offset);
myTransform.LookAt(target);
}
Awesome -- the 2nd one worked, I wasn't able to get the first to work.
I had not seen TransformDirection before, so thank you for giving me something new to check out!! :)
Cool, glad you got it working. Did you try the first one with only the Start, no FixedUpdate or Update for that matter? I didn't test it, but should work. Also, FixedUpdate is mostly for physics type updates, like when moving a rigid body. Update is recommended for smoother transform changes.
C# actually isn't my language of choice, which is part of why I was having trouble with it. So I'm guessing that the first one failed because my own lack of knowledge.
However, the 2nd one is quite smooth. I'm wondering, though, if you might have a solution to a follow-up problem?
I've asked the question here: http://answers.unity3d.com/questions/476458/slerping-camera-top-down-view-how-to-keep-it-over.html
If you know of a possible solution, that would be SUPER helpful!!