- Home /
Camera follow Player Script - Problem
Hello everyone, I'm trying to develop a script for camera that can follow player movement. I'm using this script but the camera don't do anything and consolle don't give me any error.
Here is the code:
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
public Transform Player; // Reference to the player's transform.
void Awake ()
{
//Setting up the reference.
//Player = GameObject.FindGameObjectWithTag("Player").transform;
Player = GameObject.FindWithTag ("Player").transform;
}
void FixedUpdate ()
{
TrackPlayer();
}
void TrackPlayer ()
{
// By default the target x and y coordinates of the camera are it's current x and y coordinates.
float targetX = transform.position.x;
float targetY = transform.position.y;
// Set the camera's position to the target position with the same z component.
this.transform.position = new Vector3(targetX, targetY, transform.position.z);
}
}
Someone can tell me where I'm wrong? Thanks!
Answer by robertbu · May 19, 2014 at 06:03 AM
You pull the transform apart and put it back together, but you don't use the 'Player' transform when moving. To get what I think you want, change lines 23 and 24 to:
float targetX = Player.position.x;
float targetY = Player.position.y;
Ok, it goes right! One question, is there something to smooth camera movement? Because now when it move is flickering.,Yeah, it Goes right! One question, is there something to smooth camera movement? Because now when it move is flickering.
Smoothness is usually done with Vector3.Lerp() or Vector3.$$anonymous$$oveTowards(). Replace line 27 with these lines:
Vector3 v = new Vector3(targetX, targetY, transform.position.z);
transform.position = Vector3.Lerp(transform.position, v, Time.deltaTime * speed);
Your answer
Follow this Question
Related Questions
Unassigned Reference Exception 4 Answers
How do I stop Script from making multiple Cameras? 1 Answer
Raycast not rotating with object it casts from 0 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer