- Home /
Camera following player gameObject,Camera follows player, with script attached.
I have a camera inside a player object, and that player has a script that rotates it when the mouse is moved along the X axis. The camera has a script that rotates it when the mouse is moved along the Y axis. The camera usually follows the player along the X axis, but when I enable this script it doesn't. I can put the Y axis code in the player's script, but that rotates the whole player. I can put the X axis code in both, but the camera always ends up faster than the player, even when they have the same speed set.
Here are the scripts
Script for the player
public class PlayerMovement : MonoBehaviour {
public float speed = 20.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
private CharacterController controller;
private Animator anim;
public float speedH = 10.0f;
private float yaw = 0.0f;
void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
}
void Update()
{
if (controller.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
yaw += speedH * Input.GetAxis("Mouse X");
transform.eulerAngles = new Vector3(0.0f, yaw, 0.0f);
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
Script for camera
public class Look : MonoBehaviour {
public float speedV = 10.0f;
public float maxUp = 60f;
public float maxDown = -60f;
private float pitch = 0.0f;
void Update ()
{
pitch -= speedV * Input.GetAxis("Mouse Y");
pitch = Mathf.Clamp(pitch, maxDown, maxUp);
transform.eulerAngles = new Vector3(pitch, 0.0f, 0.0f);
}
}
Answer by RocketFriday · Sep 06, 2018 at 10:32 AM
When you parent an object to another object it automatically inherits all rotation. So when your player rotates with the x-axis from the mouse, the camera will too. By adding the x-axis code to the camera you're adding extra rotation on top of that.
as for the issue with it not rotating after enabling the script.
don't do:
transform.eulerAngles = new Vector3(pitch, 0.0f, 0.0f);
instead do:
transform.eulerAngles = new Vector3(pitch, transform.eulerAngles.y, 0.0f);
Your answer
Follow this Question
Related Questions
Making object Clamp to Look Rotation of Camera 1 Answer
Automatic 3rd person camera 1 Answer
Free Orbit Cam and Mouse Aim Cam aren't working together 0 Answers
Camera rotation 0 Answers