0
votes

I've written some code for my camera so that it follows my character (i'm making a 3D side-scrolling endless-runner/platform game).

It follows the player but its really jumpy and not smooth at all. How can i fix this?

I am avoiding parenting to the character because i don't want the camera to follow the player when it jumps upwards.

Here is my code:

using UnityEngine;
using System.Collections;

public class FollowPlayerCamera : MonoBehaviour {


    GameObject player;

    // Use this for initialization
    void Start () {

    player = GameObject.FindGameObjectWithTag("Player");

    }

    // Update is called once per frame
    void LateUpdate () {

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





}
1
Then you need to make up an algorithum to tether your camera, but for it to smooth out the changes, so that it catches up, or moves up/down more gracefully, and less like its having a fit such as if camera.y > person.y then if diff>100 camera.y -10 else camera.y -1 (so it moves a lot more if there is a big fall for example, but will catch up for each frame it redraws.. but, doesnt move violentlyBugFinder

1 Answers

1
votes

I recommend using something like Vector3.Slerp or Vector3.Lerp instead of assigning the position directly. I included a speed variable, you can adjust it higher or lower to find the perfect speed for your camera to follow the player at.

using UnityEngine;
using System.Collections;

public class FollowPlayerCamera : MonoBehaviour {

public float smoothSpeed = 2f;
GameObject player;

// Use this for initialization
void Start () {

player = GameObject.FindGameObjectWithTag("Player");

}

// Update is called once per frame
void LateUpdate () {

transform.position = Vector3.Slerp(transform.position, new Vector3(player.transform.position.x, transform.position.y, transform.position.z), smoothSpeed * Time.deltaTime); 
}
}

Hopefully this helps you get closer to your solution.