Hi, I have a GameObject called ‘body’ and a GameObject called ‘aCamera’. What I need is when the ‘body’ moves and rotates, I need the ‘aCamera’ move and rotate along with the ‘body’. I cannot make the aCamera object a child of the ‘body’ object because I do not want the Y rotation.
The script I’ve created does the trick however it’s not that precise. So I would like to know if there is a better way to do it or maybe I need some small change. There is a offset difference between ‘body’ and ‘aCamera’, this is Vector3(0, 1.406, 0.153).
Thanks a lot already!
using System;
using Entities;
using UnityEngine;
public class PlayerBodyPositionSync : MonoBehaviour
{
[SerializeField] private GameObject body;
[SerializeField] private GameObject aCamera;
private TransformClone _bodyTransformClone;
private Vector3 _oldBodyPosition;
private void Awake()
{
_bodyTransformClone = body.transform.Clone();
var forward = aCamera.transform.forward;
aCamera.transform.forward = new Vector3(forward.x, forward.y, forward.z);
}
private void FixedUpdate()
{
SyncPositionAndRotationWithVrCamera();
}
private void SyncPositionAndRotationWithVrCamera()
{
// When there is no rotation difference skip this function
if (Math.Abs(Math.Round(aCamera.transform.localEulerAngles.y, 4) -
Math.Round(body.transform.localEulerAngles.y, 4)) > 0.0f)
{
// calculate angle between the two points
var bodyRotation = body.transform.rotation;
var angle = Quaternion.Angle(_bodyTransformClone.Rotation, bodyRotation);
var isRightRotation = IsRotationToTheRight(_bodyTransformClone.Rotation, bodyRotation);
_bodyTransformClone = body.transform.Clone();
RotateVrCameraWithBody(isRightRotation ? angle : -angle);
var forward = body.transform.forward;
aCamera.transform.forward = new Vector3(forward.x, aCamera.transform.forward.y,
forward.z);
}
var position = body.transform.position;
var newPosition = position - _oldBodyPosition;
aCamera.transform.position += new Vector3(newPosition.x, newPosition.y, newPosition.z);
_oldBodyPosition = position;
}
private void RotateVrCameraWithBody(float angle)
{
aCamera.transform.RotateAround(body.transform.position, Vector3.up, angle);
}
private bool IsRotationToTheRight(Quaternion from, Quaternion to)
{
var fromY = from.eulerAngles.y;
var toY = to.eulerAngles.y;
var clockWise = 0f;
var counterClockWise = 0f;
if (fromY <= toY)
{
clockWise = toY - fromY;
counterClockWise = fromY + (360f - toY);
}
else
{
clockWise = (360f - fromY) + toY;
counterClockWise = fromY - toY;
}
return (clockWise <= counterClockWise);
}
}