hckrieger
hckrieger

Reputation: 81

How to move the camera up the Y axis only when the player reaches the top 1/2 of the screen in Unity C#

This is for a 2D platform game.

I don't want the camera to move up the Y axis when the player jumps. I only want it to move when the player to the upper part of the screen so it can scroll up to vertical platforms and ladders.

Does anybody know what to enter in the code and the Unity editor so that can be done?

Here's the code I have so far in the camera script.

public class CameraControl : MonoBehaviour {

    public GameObject target;
    public float followAhead;
    public float smoothing;

    private Vector3 targetPosition;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        targetPosition = new Vector3 (target.transform.position.x, transform.position.y, transform.position.z);

        if (target.transform.localScale.x > 0f) {
            targetPosition = new Vector3 (targetPosition.x + followAhead, targetPosition.y, targetPosition.z);
        } else {
            targetPosition = new Vector3 (targetPosition.x - followAhead, targetPosition.y, targetPosition.z);
        }

        transform.position = Vector3.Lerp (transform.position, targetPosition, smoothing * Time.deltaTime);
    }
}

Upvotes: 0

Views: 1261

Answers (1)

Galandil
Galandil

Reputation: 4249

I guess you have a bool tied to the jump which triggers the jumping animation.

So, in the Update() of the camera you can do something like this:

void Update() {
    // Update camera X position
    if (isPlayerJumping) return;
    // Update camera Y position
}

This way, you update the Y position of the camera only if the player isn't jumping, while still updating the X position in all cases (even while jumping).

Upvotes: 1

Related Questions