0
\$\begingroup\$

I've been working on a 2D Platformer and i succeeded in setting up a script for my Main Camera to follow my Player gameobject using transform positions.

Now when my character is near the sides (or ends) of my level, it's showing dead space, blue space if you will. I want my camera to stop when it reaches the edges of my background sprite(end of level).

Here's my script that is attached to the Main Camera so far:

using UnityEngine;
using System.Collections;

public class CameraSmoothFollow : MonoBehaviour
{

public GameObject cameraTarget; // object to look at or follow
public GameObject player; // player object for moving

public float smoothTime = 0.1f;    // time for dampen
public bool cameraFollowX = true; // camera follows on horizontal
public bool cameraFollowY = true; // camera follows on vertical
public bool cameraFollowHeight = true; // camera follow CameraTarget object height
public float cameraHeight = 2.5f; // height of camera adjustable
public Vector2 velocity; // speed of camera movement


private Transform thisTransform; // camera Transform

// Use this for initialization
void Start()
{
    thisTransform = transform;

}

// Update is called once per frame
void Update()
{
    if (cameraFollowX)
    {
        thisTransform.position = new Vector3(Mathf.SmoothDamp(thisTransform.position.x, cameraTarget.transform.position.x, ref velocity.x, smoothTime), thisTransform.position.y, thisTransform.position.z);
    }
    if (cameraFollowY)
    {
        // to do  
    }
    if (!cameraFollowX & cameraFollowHeight)
    {
        // to do
    }

}

}

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

In your Update Function, You need limit transform.position.x range, like this:

void Update() {
    float targetX =  Mathf.Max(levelMinX, Mathf.Min(levelMaxX, cameraTarget.transform.position.x));
    float x = Mathf.SmoothDamp(thisTransform.position.x, targetX, ref velocity.x, smoothTime);

}
\$\endgroup\$
1
  • \$\begingroup\$ clamp() - 6 of one, half a dozen.. \$\endgroup\$
    – Jon
    Commented Apr 4, 2015 at 19:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .