1
\$\begingroup\$

im new to unity scripting, and now am building upon "Roll a Ball" example in unity training. I wanted to make the camera rotate around the ball in the scene in Y axis, when mouse is moved, and watched some tutorials on it, and eventually wrote the code below. but it doesn't rotate around the ball. instead it does a simple rotate in place. camera still moves with the ball though. what am i doing wrong?

public class CameraController : MonoBehaviour {

    public GameObject Player;
    private Vector3 offset;

    public float moveSpeed;
    private Vector3 point;


    void Start () {
        offset = transform.position - Player.transform.position;

        point = Player.transform.position;
        transform.LookAt(point);
    }

    void Update()
    {
        float mouseMovement = Input.GetAxis("Mouse X");

        transform.RotateAround(point, new Vector3(0f, mouseMovement, 0f) , moveSpeed * Time.deltaTime);
    }


    void LateUpdate()
    {
        transform.position = Player.transform.position + offset;

    }
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Your problem comes from setting the position of the camera in late update. Change your LateUpdate code to something like this and remove the code from Update

 void LateUpdate()
    {
        offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
        transform.position = player.position + offset;
        transform.LookAt(player.position);
    }
\$\endgroup\$
7
  • \$\begingroup\$ ahh. thought op couldn't just rotate with his current code. +1 from me. (y) \$\endgroup\$ Commented Jul 8, 2016 at 8:44
  • \$\begingroup\$ thanks a lot man, that did exactly what i wanted. though is there any way to tweak my current code to do the same? im only asking for learning purposes. \$\endgroup\$
    – MrChips
    Commented Jul 8, 2016 at 8:54
  • \$\begingroup\$ Well I dont think so because your current code fights for the position of the camera object. By fight I mean that both RotateAround and the code that follows the player set the position thus resulting in the cam rotating in place. The code I provided keeps the rotation and positioning separate which is what you want. Read this to completely understand RotateAround. link \$\endgroup\$
    – Uri Popov
    Commented Jul 8, 2016 at 9:09
  • \$\begingroup\$ i see. well thanks again. and i hope i don't be too much of a bother, but one more question. what exactly " * offset" does at the end of the first line? or more specifically, the " * " in lines like this in general. \$\endgroup\$
    – MrChips
    Commented Jul 8, 2016 at 9:30
  • \$\begingroup\$ * simply means multiplication. For example if you do print(2*2) this will output 4 to the console. \$\endgroup\$
    – Uri Popov
    Commented Jul 8, 2016 at 9:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .