Night.owl
Night.owl

Reputation: 121

Camera following player - issue being not smooth

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





}

Upvotes: 0

Views: 190

Answers (1)

Allen
Allen

Reputation: 567

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.

Upvotes: 1

Related Questions