- Home /
How to make the camera follow the player while still being able to be rotated?
In a camera script, I want the camera to be able to rotate around the player on the y-axis. This works fine, but when I make the camera follow the player, it won't be able to rotate because it's constantly being set to a certain position. How can I make the camera follow the player, but still rotate around the player as well? using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CameraScript : MonoBehaviour {
public Transform target;
public Vector3 offset;
public float yawSpeed = 100f;
private float yawInput = 0f;
private bool mouseDown = false;
void LateUpdate()
{
//transform.position = target.position + offset;
transform.LookAt(target);
if (Input.GetMouseButtonDown(1))
{
mouseDown = true;
}
if(Input.GetMouseButtonUp(1))
{
mouseDown = false;
}
if (mouseDown)
{
yawInput = Input.GetAxis("Mouse X") * yawSpeed * Time.deltaTime;
transform.RotateAround(target.position, Vector3.up, yawInput);
target.gameObject.transform.rotation = Quaternion.Euler(0, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
print(target.gameObject.transform.rotation.y);
}
}
}
Thanks!
Answer by black_sheep · Jan 06, 2018 at 09:34 AM
I suppose by the Y axis you mean to rotate AROUND the player, not going up and down, neither getting closer or further.
I'll do it by having a transform poiting to the the angle we are looking from the player (0 is we're facing him, 90 is besides, 180 is on the back), than going forward, making at look at the player, than making it the camera transform. I didn't test the code but i think it Works. Anyway i made my point.
using UnityEngine;
public class CameraTrack : MonoBehaviour {
public float rotateSpeed=4.0f; //Time in seconds it takes for the camera to rotate around the Player
public float distance=4.0f; //Distance from the camera to the player
Transform player; //Make the camera a child object of the player in the inspector
Transform auxT;
float currentRot;
void Start(){
player=transform.root;
}
void Update(){
currentRot += (input.GetAxis("Mouse X") * (360/(rotateSpeed*time.deltaTime));
currentRot %= 360;
auxT = player;
auxT.rotation.y = currentRot;
auxT.position = Vector3.forward * distance;
auxT.lookAt(Player);
}
transform = auxT;
}
Your answer
Follow this Question
Related Questions
Rotating the camera over a period of time 1 Answer
Forward and back movements with a camera emulating an isometric view 1 Answer
Why is my camera not snapping 90 degrees? 0 Answers
[JS] Custom camera rotation resets on Var change? 0 Answers
How to create a panning, rotating camera with Cinemachine Freelook camera? 0 Answers