1
votes

I can't get my camera's position to move with the player.

This is the CameraController.cs

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour
{

    public GameObject Player;
    private Vector3 offset;
    void Start()
    {
        transform.position = Player.transform.position;
    }

    void LateUpdate()
    {
        transform.position = Player.transform.position;
        Debug.LogError(transform.position);
    }
}

The script is a component of the main camera. The camera is not a child of the player object or vice versa.

The debugging says that the position is being updated to the player's position, but when the game is run the camera is static and doesn't move from its initial starting point.

3
This looks like it should work. It's very odd that the debug of the camera's position shows that it is the same as the player's if it isn't visibly changing. I think your error must be elsewhere in your session. Your start function and the deceleration of the member variable offset are unnecessary but this shouldn't have any effect on what you are trying to achieve. Are there any other scripts in your session that change the position of your camera? Are you getting any errors in the console? - Danny Herbert

3 Answers

1
votes

Try this:

using UnityEngine;
using System.Collections;

public class CameraController: MonoBehaviour {

public GameObject Player;
private Vector3 offset;

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

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

The offset is distance between camera and player.

Another way is by making camera a child of player.

1
votes
using UnityEngine;
using System.Collections;

public class CameraFollower : MonoBehaviour
{
    public Transform thePlayer;

    private Vector3 offset;

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

    void Update()
    {
        Vector3 cameraNewPosition = new Vector3(thePlayer.position.x + offset.x, offset.y, thePlayer.position.z + offset.z);
        transform.position = cameraNewPosition;
    }
}
0
votes

Thanks so much for posting and trying to help. The problem was that I was trying to get the script to move the camera when it was in a Virtual Reality supported environment. I have found that the way the camera behaves, and subsequently how the camera is moved, is different when it is in a VR environment and the camera needs to be a child of an object to be moved and cannot be moved via scripts.