Unity - 如何根据当前位置计算带有偏移量的目标位置?

5
我要实现的目标是计算一个物体应该移动到的位置,该位置基于其当前位置偏移。我有一个预定义的向量偏移量为 (2, 0, 4),假设我的目标位置只是0,0,0,根据我的物体相对于目标位置的方向,需要使用预定义的偏移量从目标位置计算出最终位置。
例如,如果我的物体正好在目标后面,则最终位置应该是 (2, 0, -4)
请注意,不需要考虑旋转。我只需要一个新的位置来移动,并保持原始方向朝向目标位置。我不确定如何进行计算。
private void MoveToTargetWithOffset(Vector3 targetPos) {
    Vector3 offset = new Vector3(2, 0, 4);
    Vector3 currentPos = transform.position;
    Vector3 finalPos = Vector3.zero;

    // Calculate the final position. The position should be a point closest to the currentPos with the offset applied.
    transform.position = finalPos;
}

这些三角形是我想要移动的物体。虚线显示它们应该基于预定义的对象所在的位置。

image

1个回答

10
这里有一张图片来解释它。

enter image description here

这是一段代码片段,与图片相符:

public class HoverFromTarget : MonoBehaviour {
    public Transform target;
    public float preferredDistance = 5.0f;
    // Use this for initialization
    void Start () {
        //Considering this object is the source object to move
        PlaceObject ();
    }

    void PlaceObject(){
        Vector3 distanceVector = transform.position - target.position ;
        Vector3 distanceVectorNormalized = distanceVector.normalized;
        Vector3 targetPosition = (distanceVectorNormalized * preferredDistance);
        transform.position = targetPosition;
    }
}

这是一个很好的答案,但是由于单词“target”被多次用于表示不同的含义,所以有些难以理解。但这并不是你的错,因为问题本身就表述得有些混乱。通常情况下,你想要把“target”保存到你想去的地方,而不是你来自哪里的地方。 - mLstudent33

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接