- Home /
Keeping camera stay put in the y position
Hello! I have an endless runner where I have a simple script to follow the player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cam : MonoBehaviour {
public GameObject player;
private Vector3 offset;
void Start () {
offset = transform.position - player.transform.position;
}
void LateUpdate () {
transform.position = player.transform.position + offset;
}
}
So I have a long flat platform where the player constantly moves forward on it, having to dodge obstacles. I am trying to make it to where when the playerfalls of the edge, the camera stops where it is and doesn't follow the player. Such as saying when the player goes below -1 Y, the camera stops, but how would I put that in code? Thanks.
Comment
Answer by Dray · Jan 09, 2018 at 11:22 AM
float minY = -1;
void LateUpdate () {
transform.position = player.transform.position + offset;
if (transform.position.y < minY) {
transform.position.y = minY;
}
}
Answer by dev-waqas · Jan 09, 2018 at 11:37 AM
The good solution is not to Update y-axis of camera in first place. So simply Update Position like this.
void LateUpdate () {
transform.position = new Vector3( player.transform.position.x+ offset.x , this.transform.position.y+ offset.y , this.transform.position.z+ offset.z);
}