- Home /
Dynamic Camera Height Depending On Player / Terrain Height
Ok, So I have this script that I made, it basically follows the Player but adds some Lerping to make it smooth. But I have been having trouble making it change height when my player goes up a ramp. I would like it so the camera (Perspective) is always 12 world units above my player. Here is the camera script that I have constructed.
public class GameCamera : MonoBehaviour {
private Vector3 cameraTarget;
private Transform target;
void Start () {
}
void Update () {
if(PlayerPrefs.GetString("Player Joined") == "True"){
target = GameObject.FindGameObjectWithTag("Player").transform;
cameraTarget = new Vector3(target.position.x,transform.position.y,target.position.z);
transform.position = Vector3.Lerp(transform.position,cameraTarget,Time.deltaTime * 8);
}
}
}
I cannot simply take target.position.y and add 12 because it gives me a temporary variable error. Prehaps one of you smarties can shine some light on the situation.
Thanks
Answer by tanoshimi · Jun 07, 2014 at 02:33 PM
Replace:
cameraTarget = new Vector3(target.position.x,transform.position.y,target.position.z);
with:
cameraTarget = new Vector3(target.position.x,target.position.y + 12f,target.position.z);
I cant because the camera keeps zoo$$anonymous$$g out as it is in an update loop.
Why would it keep zoo$$anonymous$$g out? Please check you have copied my code correctly, because it works for me.
The code is copied correctly, the camera is not a child of the player if that makes any difference. The camera keeps going up and up for ever!
The camera shouldn't be a child of the player. This script should be attached to the camera and the player should be tagged "Player". In the Update() loop you're then lerping the camera from it's current position to 12 units above the player's position.
The only way I can see that your camera would keep travelling upwards is if you were using transform.position.y + 12f
ins$$anonymous$$d of target.position.y + 12f
Thank you, that solved the problem. Guess I just didn't look at your change close enough. Thanks and sorry for any extra trouble I caused you.
Your answer
Follow this Question
Related Questions
Camera stay on same Y axis 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity not dividing correctly C# camera pixel width & height 1 Answer