Moving camera on only one axis.

Hi guys,

I’ve been going through the forums and documentation for the past hour trying to figure this out but I’ve come to the conclusion that I’m a bit too clueless as of now to understand what people are saying.

So I decided to bite the bullet and just post.

I’m trying to make a rolling ball maze game thing, based off the “Roll a Ball” tutorial that you get with Unity.
My plan is for you to have to move a ball through a maze that is rectangular, so you are always essentially going down, so I just wanted the camera to move on the Z axis, I’ve tried a bunch of methods I’ve read but I keep doing something wrong as it doesn’t work.

This is what I am using right now, so it follows the player as it moves around, I’m sure you all could tell that anyway.

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

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;
      
}
}

I apologise in advance for not formatting the script in, I couldn’t figure that one out.
What would the easiest way to I guess freeze the x axis be?

Many thanks!

You could edit your post, this link can explain/show you how to post code nicely on the forums: Using code tags properly

Do you want to follow only the player’s y position … keep your x & z the same?

Thanks heaps mate, I look like a fool for missing that.

After reading over the post I can definitely see that I’ve burnt myself out today as I meant to put just move along the z axis and keep y and x where they are.

Sorry for the confusion.

no problem, so maybe you want something like this?

transform.position = new Vector3(transform.position.x, transform.position.y, player.transform.position.z) + offset;

That won’t lock to the original X and Y unless those components in offset are 0.

You’d want something like this

var pos = transform.position + (transform.position - player.transform.position);
pos.x = transform.position.x;
pos.y = transform.position.y;
transform.position = pos;

Right, I was thinking of that and neglected to comment about it.