- Home /
Turning a character to match camera rotation
Hi all, apologies if this is a stupid question. I'm working on a 3rd person platformer, and I have the camera parented to an empty GameObject that is parented to the character. This allows me to move the camera backwards and forwards without effecting the rotation, which is done via mouse (the mouselook script is attached to the GameObject, rather than the camera). What I'd like to do, is to have the character stand still when the camera rotates around him, but then turn to face away from the camera as soon as any movement button is pressed. I thought I had it working well, but then I realised that if I rotate the camera around him several times, when I start moving he'll do those extra spins rather than just turning the difference. I tried all sorts of things like dividing the camera's rotation by 360 to get the number of spins etc. but I just feel like I'm on the wrong track there and can't quite get the right result. I'm sure I'm missing a very simple bit of code that I just can't seem to find.
Any help would be much appreciated.
cameraYRotation = cameraObject.GetComponent(Mouselook).currentYRotation;
playerRotation = Mathf.SmoothDamp(playerRotation,playerTargetRotation,playerRotationV,moveSmoothDamp);
if (Input.GetAxis("Vertical") + Input.GetAxis("Horizontal") != 0)
playerTargetRotation = cameraYRotation;
transform.rotation = Quaternion.Euler(0, playerRotation, 0);
If I can't manage to peg this down, I'll probably just add in this:
if (cameraYRotation - playerRotation > 30)
playerRotation = cameraYRotation - 30;
if (playerRotation - cameraYRotation > 30)
playerRotation = cameraYRotation + 30;
Which just means he'll turn with the camera 30 degrees behind.
If I were you, I wouldn't make the camera an explicit transform child of the character. If you want to avoid the camera rotating when the character turns, make the camera centre object have no transform parent, but have a script on it which sets its position to that of your character every Update.
Thanks for that syclamoth, I probably should have said 3rd person shooter rather than platformer. Anyway, I ended up adding that last bit (except 90 ins$$anonymous$$d of 30) and it seems to work pretty well after a couple of tweaks. But don't worry, I'm sure I'll have more questions soon!
Your answer
![](https://koobas.hobune.stream/wayback/20220613022610im_/https://answers.unity.com/themes/thub/images/avi.jpg)