- Home /
Camera rotating super fast when trying to match the camera and players Y euler angle.
I'm still a noob at this so bare with me. I'm trying to get my player to move in the Camera's direction that it is facing. I heard something about how euler angles can help. But whenever I start the game, the smallest mouse movement makes the camera go insane. Here's my code so far.
#pragma strict
var TheCamera : GameObject;
function Start () {
Screen.showCursor=false;
}
function Update () {
transform.eulerAngles.y= TheCamera.transform.eulerAngles.y;
if(Input.GetKey(KeyCode.W)){
transform.Translate(0,0,0.2);
}
}
If you have any other questions just ask me. Thank you.
Answer by aldonaletto · Nov 03, 2013 at 02:52 AM
First of all, reading eulerAngles is always a bad idea: there are several different XYZ combinations that result in the same rotation, and according to Murphy's laws Unity will return the wrong combination at the worst possible times. The reciprocal isn't true: setting eulerAngles works fine - provided that you never assign a single axis like you're doing in this code: always assign a whole Vector3 to eulerAngles.
Second: if the camera is childed to the player, the code above will drive it nuts (and you too). If the camera isn't a child of the player, then you can get its forward direction, zero Y in order to keep only the horizontal part, and assign it to transform.forward:
public var speed: float = 10; // add the speed variable
function Update () {
var dir: Vector3 = TheCamera.transform.forward; // get the camera's forward...
dir.y = 0; // keep it strictly horizontal
transform.forward = dir; // player turns in the direction found
if (Input.GetKey(KeyCode.W)){
// move at constant speed
transform.Translate(0, 0, speed * Time.deltaTime);
}
}
Notice that I added a speed variable, which's multiplied by Time.deltaTime in order to keep a framerate-independent movement.
Thanks bro, worked like a charm! I'm never going to put a camera as a child again.
On the contrary: the camera is usually childed to the player in FPS games, like in the First Person Controller standard prefab. The solution is to turn the camera only up and down, and turn the whole character left/right - since the camera is a child of the character, it will turn left/right too. The First Person prefab does this by using two $$anonymous$$ouseLook scripts: one attached to the character that only rotates about world Y, and the other attached to the camera and limited to rotate about local X only.
Your answer
![](https://koobas.hobune.stream/wayback/20220613121136im_/https://answers.unity.com/themes/thub/images/avi.jpg)