sam nikzad
sam nikzad

Reputation: 1360

Follow Player By Camera in 2D games

I used This code for my MainCamera for following the player in my 2d game in Unity5 :

using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {

    public float dampTime = 0.15f;
    private Vector3 velocity = Vector3.zero;
    public Transform target;

    // Update is called once per frame
    void Update () 
    {
        if (target)
        {
            Vector3 point = GetComponent<Camera>().WorldToViewportPoint(target.position);
            Vector3 delta = target.position - GetComponent<Camera>().ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
            Vector3 destination = transform.position + delta;
            transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
        }

    }
}

It work fine But player is in middle of screen allways . i wan player be in down of screen and my sprite for show Earth of my game will stick below the camera . i mean better in following pictures:

What I Want :

enter image description here

The Result :

enter image description here

Upvotes: 0

Views: 660

Answers (1)

Gunnar B.
Gunnar B.

Reputation: 2989

You can add a vertical offset to the calculation. Just adding it to destination should do that I think.

Vector3 destination = ...
destination.y += someOffset;
transform.position = Vector3.SmoothDamp(...);

Otherwise you could also add an empty gameobject to the player gameobject and use that as your target.

One thing that you might need to consider is the resolution.

Upvotes: 1

Related Questions