Vector2 Lerp. Probably a simple solution C#

Hey Guys, Im Sorry if this is a silly question and thank you so much for having a look to see if you can help me out.

i’m trying to create a very simple 2D runner iOS game, at the moment i have a Player whom runs to the right of the screen continuously at the “speed” Variable… and for debugging i created a camera that moved to the right at the same speed,
Obviously this is not ideal as the player might run away from the camera if there is any lag or hieriechy when the scripts load.

So i’m trying to get the Camera to constantly follow the player and never get too far way.
Ive never used any lerps before and im not sure if they are the way to go or not but here is what i was thinking.

using UnityEngine;
using System.Collections;

public class MainCamera : MonoBehaviour {
	
	public Transform Player;
	public int CameraSpeed = 5;
	private Vector2 Currentposition;
	private Vector2 EndPosition;


	void Start() {
		Currentposition = transform.position;
		EndPosition = Player.transform.position;
	}

	// Update is called once per frame
	void FixedUpdate () {
		transform.position = Vector2.Lerp (Currentposition, EndPosition, 1.0f * Time.fixedDeltaTime);
		//transform.Translate (Vector2.right * Time.deltaTime * CameraSpeed);

	}
}

Currently the Camera moves to a position at the start then just stays there.
Like i said, sorry if its a stupid question, if you can offer any assistance that would be much appreciated, thankyou. :slight_smile:

#Note: Im also planning on implementing Zoomed in / Zoomed out position variables.

I have this script attached to my Camera to follow my target. You can tweak it a little to achieve your desired result.

public class Follow : MonoBehaviour
{
	public GameObject target;

	// Update is called once per frame
	void FixedUpdate()
	{
		Vector2 pos = Vector2.Lerp ((Vector2)transform.position, (Vector2)target.transform.position, Time.fixedDeltaTime);
		transform.position = new Vector3(pos.x, pos.y, transform.position.y);
	}
}

Yes, to only follow the ‘x’ position:

void FixedUpdate () {
   Vector3 pos = transform.position;
   pos.x = Player.position.x;
   transform.position = Vector3.Lerp (transform.position, pos, CameraSpeed * Time.fixedDeltaTime);
 
}

Hi,

When you say

So i’m trying to get the Camera to constantly follow the player

I answer “Why don’t you attach the camera to the player hierarchy?”. Then moving the player will actually move the camera. The camera will ALWAYS follow the player.

If you need some introduction camera moves (like a scrolling view of the level) you just have to attach the camera to the player hierarchy at the end of the first animation using the parent property. Something like :
Camera.main.transform.parent = my_player.transform;

You still can use Vector2.Lerp (if you really want to) on the camera localPosition to add some camera effects during the run.

I hope it helps.