Search code examples
c#androidunity-game-enginescriptingperspectivecamera

Stop camera from moving on x axis


So I have a rocket (player) that is flying up on the Y axis. I have a camera with this script following the rocket:

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour
{
public GameObject player;
private Vector3 offset;

// Use this for initialization
void Start () 
{
    offset = transform.position;
}



// Update is called once per frame
void LateUpdate () 
{
    transform.position = player.transform.position + offset;
}
}

How can I stop the camera from moving on the x axis? I only want it to follow the rocket upwards on the Y axis. I tried adding a rigid body and blocking the X axis there but that didn't work. Any ideas how to do this in script? Thank you!

P.S. I'm kinda new to scripting, please tell me how to implement the extra code.


Solution

  • Well, a simple way to lock your camera into just one axis would be to change the code you provided above to this:

    using UnityEngine;
    using System.Collections;
    
    public class CameraController : MonoBehaviour
    {
    public GameObject player;
    private Vector3 offset;
    
    // Use this for initialization
    void Start () 
    {
        offset = transform.position;
    }
    
    
    
    // Update is called once per frame
    void LateUpdate () 
    {
        transform.position = new Vector(
        offset.x, player.transform.position.y + offset.y,
        offset.z);
    }
    }
    

    This should make the camera only go up/down along with the rocket, but not move on either the x or z axis. If this isn't exactly what you were trying to achieve, leave a comment and I'll take a look