use*_*989 2 c# math vector unity-game-engine
我想要实现的是计算对象移动到的位置,该位置具有基于其当前位置的偏移量。
我有一个预定义的 Vector3 偏移量,(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;
}
Run Code Online (Sandbox Code Playgroud)
三角形是我想要移动的对象。虚线显示它们应该基于预定义对象的位置。
小智 5
这是一张图片来解释它。
这是根据图片的代码片段:
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;
}
}
Run Code Online (Sandbox Code Playgroud)