- Home /
how the camera will follow the rotation in one axis only?
Hi. So here is my code.
So what I am trying to do is make camera follow my player on x and z axis. And at the same time follow rotation of player on y axis only.
I have tried to do it myself but I guess I am missing something as always. Please be sure to explain the answer as I am just a student. Thx a lot
Hi bro @DrTomato
Answer by highpockets · Apr 01, 2021 at 11:22 AM
Ok, so generally the way that I approach this scenario is to add another level of control which is another game object which is right at the players position and it follows the player wherever it goes and rotates on just the y axis when the player rotates around the y axis, but does not rotate around any other axis. This is just an empty object which we can call "CameraTarget". Do not make this object a child of the player, but make the camera a child of the "CameraTarget" object and place the camera at the offset you want it in the scene view before the game starts so the local position is predetermined (no need to add an offset in the script). Now instead of your Camera following the player, it is following this invisible object at the player's origin. So you need to track the player like so:
public class CameraFollow : MonoBehaviour
{
public Transform camTarget;
public Transform player;
private void LateUpdate()
{
camTarget.position = player.position;
//rotate to face the camera target to face the same forward direction as the player
camTarget.rotation = Quaternion.LookRotation(player.forward, Vector3.up);
}
}
This is fairly basic, but it is a start. From here you may want to dampen the movement of the camera and so instead of the camera as a child of the Camera Target, you make another empty object a child of the Camera Target and you place it where the normal camera with the offset should be and then have this script above on this new object and make a smooth damp script for the camera to follow this new object and include a look at function so the camera stays locked onto the player pos..
EDIT: I edited the code, little bug.
Hi.. so it did not actually worked out for me. Here is what I did, I made a new gameobject(cameraTarget) and set it to my player's position. Then I made my camera child of cameraTarget. Then I applied your script (camfollow2) and rigidbody to cameraTarget. By using rigidbody I froze it's rotation on x and z axis.
Here is everything for better understanding.
Ok, not sure what didn’t work out for you. A rigidbody seems a little overkill for what you’re trying to accomplish, but as long as you got it working. A rigidbody is meant to be used with the physics engine FYI
Your answer
