- Home /
Stop camera from moving when parent rotates forward
All code in C#. I am making a 3rd person camera system. I have added rotation to a cube and this all works fine as I want it this is only for reference purposes so you can see what the box is doing, see code below:
public float speed = 6.5f;
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetAxis("RightStickVertical") < 0f)
{
rigidbody.AddTorque(transform.right * speed);
}
else if (Input.GetAxis("RightStickVertical") > 0f)
{
rigidbody.AddTorque(transform.right * -speed);
}
}
}
I have added a camera to the cube i.e. made it the child of the cube so the camera will follow the cube. To keep the camera facing the same direction (forward) I have used Quaternion.
The problem comes when the box rotates forward to move forward the camera also rotates with it i.e. the cube rotates 90 degrees forward the camera is now positioned over head. I want the camera to remain behind the cube at all times and only move forward with the cube and not up and over when the cube moves.
I am aware that a way of doing this is to make it so if the cube moves 90 degrees forward for example the camera moves 90 degrees backward so it remains in the same position, however I don't know how to do this.
Any help for any type of solution would be appreciated thanks.
Answer by amazingdude123 · Nov 02, 2014 at 06:30 PM
I have fixed this problem. I created an empty game object and in the update method I transformed it's position to that of the cube. I then made the camera a child of the empty game object and this works perfectly. Here is the code for instantly moving the empty game object to the cube in case anybody needs it:
public GameObject box;
void Update ()
{
transform.position = box.transform.position;
}
Place the object you want the empty game object to transform to in the inspector in unity.