简体   繁体   中英

Vector3.Lerp with code in Unity

I'm making a basic 2D space shooter game in unity. I have the movements working fine and the camera follows the player. I've been scratching my head over how to give the camera a slight delay from the player moving to the camera moving to catch up to it without it teleporting. I was told to use a Vector3.Lerp and tried a few things from stackoverflow answers but none seemed to work with the way my code is set up. Any suggestions? (myTarget is linked to the player)

public class cameraFollower : MonoBehaviour {
public Transform myTarget;


void Update () {
    if(myTarget != null){
        Vector3 targPos = myTarget.position;
        targPos.z = transform.position.z;
        transform.position = targPos;

        }

    }
}

If you linear interpolate (Lerp) you risk that Time.deltaTime * speed > 1 in which case the camera will start to extrapolate. That is, instead of following it will get in front if your target. An alternative is to use pow in your linear interpolation.

float speed = 2.5f;
float smooth = 1.0f - Mathf.Pow(0.5f, Time.deltaTime * speed);
transform.position = Vector3.Lerp(transform.position, targetPos, smooth);

Mathf.Pow(0.5, time) means that after 1/speed second, half of the distance to the target point will be travelled.

The idea with Lerp ing camera movement is to gradually and smoothly have the camera make its way to the target position.

The further away the camera is, the bigger the distance it will travel per frame, but the closer the camera is, the distance per frame becomes smaller, making the camera ease into its target position.

As an example, try replacing your transform.position = targPos; line with:

float speed = 2.5f; // Set speed to whatever you'd like
transform.position = Vector3.Lerp(transform.position, targPos, Time.deltaTime * speed);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM