Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

UNITY – Change Point of View (with one camera) when I press a button

while I’m studying Unity and C# (Unity Learn), I was looking for tips around this: how can I change Point of View with only One Camera?
Is it possible?

Here my code, attached to the MainCamera:

public class FollowPlayer : MonoBehaviour
{
    public GameObject plane;
    private Vector3 offset = new Vector3(0, 13, -13);
    private Vector3 change = new Vector3(0, 10, -10);

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void LateUpdate()
    {
        // Follow the player
        transform.position = plane.transform.position + offset;
        if (Input.GetAxis("Fire1") != 0)
        {
            transform.position = plane.transform.position + change;
        }
        if (Input.GetAxis("Fire2") != 0)
        {
            transform.position = plane.transform.position + offset;
        }

    }
}

What I want to do is to switch the "new Vector3" position of my Camera when I press a Button (Fire1 or Fire2)… It works just when I hold the Fire1/2 button.
How can I say to Unity to hold the position linked to the button Fire1 or Fire2?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I doing wrong?

Thanks

>Solution :

You’re overwriting any changes you make with your first line in LateUpdate.

Simplest solution is to just store the current offset being applied and change it on button press. Then every frame you can just apply whatever the current offset is. For example:

public class FollowPlayer : MonoBehaviour
{
    public GameObject plane;
    Vector3 curOffset;
    private Vector3 offset = new Vector3(0, 13, -13);
    private Vector3 change = new Vector3(0, 10, -10);

    // Start is called before the first frame update
    void Start()
    {
        curOffset = offset;
    }

    // Update is called once per frame
    void LateUpdate()
    {
        if (Input.GetAxis("Fire1") != 0)
        {
            curOffset = change;
        }
        if (Input.GetAxis("Fire2") != 0)
        {
            curOffset = offset;
        }

        transform.position = plane.transform.position + curOffset;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading