Reputation: 1
i want to rotate player body according to the rotation of the camera. like FPS game.
STEPS >>
here is my code. It is attached to body(the object i have to rotate).
private void Update()
{
transform.position = arCamera.transform.position;
transform.rotation = arCamera.transform.rotation;
}
I want to see my body when the camera facing down but body rotates according with camera so i never see the body. How can i see it? ;( Please help!
Upvotes: 0
Views: 746
Reputation: 90659
Sounds like you want your body only copy the rotation around the Y axis.
It is way easier to calculate with vectors than with quaternion rotations ;)
private void Update()
{
transform.position = arCamera.transform.position;
// Take your camera forward vector
var camForward = arCamera.transform.forward;
// erase the Y component
camForward.y = 0;
// and now make your body look into this flattened direction
transform.rotation = Quaternion.LookDirection(camForward, Vector3.up);
}
See also Quaternion.LookDirection
.
This has of course one little flaw: The moment the camera looks up or down more than 90° the body is flipping to the opposite direction. So you either want to limit the camera rotation or come up with a different approach.
E.g. assuming that it is way harder for a human being to rotate (tilt) the head more then 90° on the Z
axis, you could instead also do
private void Update()
{
transform.position = arCamera.transform.position;
// Take your camera forward vector
var camRight = arCamera.transform.right;
// erase the Y component
camRight.y = 0;
// and now align the body's right axis with this flattened direction
// Since we never touch the object's up vector this works without problems
transform.right = camRight;
}
Upvotes: 0