0
\$\begingroup\$

I'm very new to Unity and this may simply be a failure of google-fu but I hope someone here can help me out.

I'm working through a series of tutorials on how to create an RPG in Unity, making small improvements and embellishments as I go to make sure I understand the concepts.

I've built a player character with walk and run animations and a camera which follows the player around and stays aimed at the centre of the character model using the following code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollowPlayer : MonoBehaviour
{
    GameObject target;

    // Start is called before the first frame update
    void Start()
    {
        target = transform.parent.gameObject;
    }

    // Update is called once per frame
    void Update()
    {
        transform.LookAt(target.transform.position);
    }
}

The problem with this is the angle this leaves the camera pointing at in-game is to acute, making it difficult to see what is ahead of the character. How can I adjust the target of the LookAt instruction to result in a shallower X-axis rotation of the camera?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It's a bit hard to give you a specific solution without seeing a screenshot or diagram of the current vs desired behavior, but looking at your script I can suggest two general approaches to extend your camera behavior:

1) Offsetting the targeted point (changing the LookAt target, as you mentioned)

2) Offsetting the camera position or rotation

I've added these two approaches to your script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollowPlayer : MonoBehaviour
{
    GameObject target;
    //Offset variables
    Vector3  targetOffset;
    Vector3  rotationOffset;

    // Start is called before the first frame update
    void Start()
    {
        target = transform.parent.gameObject;
    }

    // Update is called once per frame
    void Update()
    {
        // adding position offset to target
        transform.LookAt(target.transform.position + targetOffset); 

        //adding rotation offset to transform
        transform.rotation += rotationOffset;
    }
}

By tweaking these variables you should be able to control the camera position and angle, so hopefully you can compose your desired view.

\$\endgroup\$

You must log in to answer this question.

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