- Home /
My camera won't move properly.
When my player object is a certain amount away from the center of the screen, a script is enabled to move the camera to the player's position, and it is only disabled when the camera is re-centered. This works when I change the camera's position to the player's position, but then it snaps to the player and I don't want that. When I use "transform.translate", the script makes the camera start slowly falling, with the player able to drag/float it around with their motion. The camera is never able to recenter like this, so the script is never disabled.
Edit: Here is my code. Like I said, it breaks when I change it to "transform.translate"
GameObject player;
void Start () {
player = GameObject.Find("Player");
}
void Update () {
transform.Translate(player.transform.position * Time.deltaTime);
}
The camera is a child of a transparent box that this script is attached to. The script is enabled when the player exits the box and disabled when the box re-centers to the player.
Without seeing your code, how can anyone know what's wrong with it?
Answer by Shifty-Geezer · Jul 18, 2017 at 10:34 AM
You are moving the camera by the player's position, not to the player's position. You need to supply Translate with a direction, as per the manual's definition. There are two easy ways to achieve what you want.
Get the direction by subtracting the camera's position from the player's position
void Update(){
transform.Translate((player.transform.position - transform.position)* Time.deltaTime);
}
Lerp (get an inbetween value) between the camera's position and the player's position.
void Update(){
transform.position = Vector3.Lerp(transform.position, player.transform.position, Time.deltaTime);
}
Thank you so much! The first solution made the movement a little twitchy, but Lerp works very well! But I have another question now: Is there a way I can alter the speed with a float variable or something? Lerp only takes 3 arguments and I tried replacing Time.deltaTime, but that makes the camera teleport.
Lerp's third parameter is relative amount of distance (always from 0 to 1) to travel. In above, higher value equals to faster speed. I'd try third parameter as something like speed*Time.deltaTime and tweak speed variable.
If you need to have full control over speed, try using (player.transform.position - transform.position).normalized*speed in first way of doing it, while first setting speed variable.
If it's the right answer and helps, you're supposed to press the tick. ;)
Your answer
Follow this Question
Related Questions
Camera smooth movement from ponint A to B 0 Answers
Problems making a smash bros like camera 2 Answers
Problems changing camera position 1 Answer
Move camera on Z axis instead of Y? 0 Answers
Making camera follow upwards 3 Answers