- Home /
Problem With 2D Camera Following Target
Hi, I'm having a problem with a camera script that I found. It is written in C# and it works perfectly except for one thing, when I run the game the camera places itself on top of the character, making it imposible to see anything except the background, how can I fix this problem?
Camera Script:
using UnityEngine;
using System.Collections;
public class SmoothCamera: MonoBehaviour {
public Transform target;
public float smooth= 5.0f;
void Update ()
{
transform.position = Vector3.Lerp (transform.position, target.position, Time.deltaTime * smooth);
}
}
Answer by 14ercooper · Aug 07, 2015 at 09:56 AM
You can try to use a new Vector3 that places the camera farther away. Using this code inside of update should have the camera follow the player with the default Z.
Vector3 targetPosMod = new Vector3 (target.position.x, target.position.y, target.position.z - 10);
transform.position = Vector3.Lerp (transform.position, targetPosMod, Time.deltaTime * smooth);
Thanks for the reply, I've finished this project long time ago, exactly like you are suggesting. Forgot to post and answer and marking it as correct. :)
Answer by IvovdMarel · Jul 08, 2014 at 02:17 AM
If you want your camera to follow your character (like in an RPG) it's easiest to create a gameobject called 'CameraTarget' and child it to your character. Move the target behind the character as far as you'd like your camera to be and then Lerp the camera towards that target. While lerping, you'll need to make sure your camera targets the character. (Use .LookAt)
Its not like in a third person game, is like in $$anonymous$$ario, platformers like that.
Answer by OxDEADBAAD · Jul 08, 2014 at 03:04 AM
Your problem seems to be that you're moving the camera to the exact position of the player, when you should instead be moving it to its x and y coordinates but keeping your camera's z intact (assuming you're placing your things "the standard way" :P)
Yeah, the problem is that I don't find a way to make it "freeze" its z position.