我正在尝试相对于另一个GameObjects本地位置设置GameObjects位置,但是我没有很多运气。通过光线投射,我可以检查播放器站在哪一侧,一切都工作正常,并且我试图根据您站在哪一侧相对于对象的本地位置创建一个变换。当不旋转此对象时,一切正常,但是当我旋转该对象时,目标位置似乎仍在世界空间中。我添加了图像来说明这种情况。
Album with images illustrating the problem
if(right)
{
Vector3 Pos1 = _pushableT.localPosition;
Pos1.x = _pushableT.localPosition.x + distBetween;
_targetPos = Pos1;
}
if (left)
{
Vector3 Pos2 = _pushableT.localPosition;
Pos2.x = _pushableT.localPosition.x - distBetween;
_targetPos = Pos2;
}
if (front)
{
Vector3 Pos3 = _pushableT.localPosition;
Pos3.z = _pushableT.localPosition.z + distBetween;
_targetPos = Pos3;
}
if (back)
{
Vector3 Pos4 = _pushableT.localPosition;
Pos4.z = _pushableT.localPosition.z - distBetween;
_targetPos = Pos4;
}
targetBallDebug.position = _targetPos;
这将适合于对象的位置,该对象看向目标,但不适用于3d空间中的旋转
using UnityEngine;
public class TrackToTarget : MonoBehaviour
{
[SerializeField]
private Transform target;
private Vector3 releativePosition;
private Quaternion targetRotationAtStartInv;
private Quaternion rotationDiffernce;
private void Start()
{
releativePosition = target.position - transform.position;
targetRotationAtStartInv = Quaternion.Inverse(target.rotation);
rotationDiffernce = target.rotation * transform.rotation;
}
private void Update()
{
transform.position = target.position - target.rotation * (targetRotationAtStartInv * releativePosition);
transform.rotation = rotationDiffernce * target.rotation;
}
}