简体   繁体   中英

How to stop camera following Y in unity

I have this code and I can't figure out how to make the camera stop following my player when he jumps, in unity3d

using UnityEngine; using System.Collections;

public class Camera2DFollow2 : MonoBehaviour {

public Transform target;
public float damping = 1;
public float lookAheadFactor = 3;
public float lookAheadReturnSpeed = 0.5f;
public float lookAheadMoveThreshold = 0.1f;

float offsetZ;
Vector3 lastTargetPosition;
Vector3 currentVelocity;
Vector3 lookAheadPos;

// Use this for initialization
void Start () {
    lastTargetPosition = target.position;
    offsetZ = (transform.position - target.position).z;
    transform.parent = null;
}

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

    // only update lookahead pos if accelerating or changed direction
    float xMoveDelta = (target.position - lastTargetPosition).x;

    bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;

    if (updateLookAheadTarget) {
        lookAheadPos = lookAheadFactor * Vector3.right * Mathf.Sign(xMoveDelta);
    } else {
        lookAheadPos = Vector3.MoveTowards(lookAheadPos, Vector3.zero, Time.deltaTime * lookAheadReturnSpeed);  
    }

    Vector3 aheadTargetPos = target.position + lookAheadPos + Vector3.forward * offsetZ;
    Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref currentVelocity, damping);

    transform.position = newPos;

    lastTargetPosition = target.position;       
}

}

Try

Vector3 aheadTargetPos = target.position + lookAheadPos + Vector3.forward * offsetZ;
Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref currentVelocity, damping);
newPos.y = transform.position.y;
transform.position = newPos;

or

Vector3 aheadTargetPos = target.position + lookAheadPos + Vector3.forward * offsetZ;
aheadTargetPos.y = transform.position.y;
Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref currentVelocity, damping);
transform.position = newPos;

You can set a minimum threshold value for the Y value of character. When characters jump you can save that transform point y and look for the distance between that point and character position.y If the character exceeds that threshold, than your camera can follow the character. Also, you can consider using Cinemachine. It is very powerful. ( https://unity.com/unity/features/editor/art-and-design/cinemachine )

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