- Home /
Allow both turning of the mouse and turning of the player to keep the camera pointing towards the player
Hi all, I've followed many tutorials for camera controllers, but because my game has three different modes which are switched between, I can't find any tutorial that satisfies my needs (third person, first person, shoulder view, and moba/rts view).
Therefore, I decided to try and create it myself.
Here is my code:
public void LateUpdate ()
{
this.ChangeCameraMode(); //Change bewteen first person, third person, and moba mode
//If we're in all modes, except moba mode, we want our camera to rotate as we rotate.
if (this.playerScript.cameraType != CameraType.MobaMode)
{
this.x += Input.GetAxis("Mouse X") * 5;
Quaternion rotation = Quaternion.Euler(0, x, 0);
Vector3 newVector = rotation * this.offsetPos;
Quaternion oldRotation = transform.rotation;
transform.position = this.playerTransform.TransformPoint(newVector);
transform.rotation = rotation; //(A) Works great for turning mouse, but turning the player doesn't point the camera to the player
transform.forward = this.playerTransform.forward; //(B) works great for turning the player, but turning the mouse doesn't point the camera to the player
}
else
{
//If we're in moba mode, we want the camera to follow, but not to rotate.
transform.position = this.playerTransform.position + this.offsetPos;
transform.rotation = Quaternion.Euler(this.offsetRot.x, this.offsetRot.y, this.offsetRot.z);
}
}
So the moba view works perfectly, it looks from above, and follows the player.
If i use the code marked (A), we can turn the mouse, and the camera rotates around the player, and keeps pointing at the player. However, when I turn the player, the camera rotates correctly, but is no longer pointing towards the player.
If I use the code marked (B), we can turn the player, but while turning the mouse correctly rotates the camera around the player, it does not point at the player.
Does anyone know how I can get them to work well together? Imagine a game like World of Warcraft, where if you turn your character the camera will also turn, but you can also hold right click and rotate the camera with the mouse.
Please note, I can't use transform.LookAt
because that would make the shoulder view not work - it would put the character in the center.
Thanks!
Answer by Kevin-Mallinson · Nov 13, 2018 at 09:49 AM
I found the solution:
//Combine the rotation of the mouse with the rotation of the player
//effectively making it possible to rotate the player and mouse at the same time
transform.rotation = this.playerTransform.rotation * rotation;
Note that * is not multiplication.
Your answer
Follow this Question
Related Questions
How to make my Camera Controller look at target 0 Answers
I only rotated X, but Y and Z are shifting as well when I play the game. 1 Answer
Free camera look question 2 Answers
Camera stucks at the spawn position 1 Answer
How to rotate my camera? 2 Answers