Unity - How to calculate a target position with offset based on the current position?

12,776

Here's an image to explain it.

enter image description here

Here's a code snippet according to the picture:

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;
    }
}
Share:
12,776

Related videos on Youtube

user1849989
Author by

user1849989

Updated on June 04, 2022

Comments

  • user1849989
    user1849989 almost 2 years

    What I am trying to achieve is to calculate a position for an object to move to which has an offset based on its current position.

    I have a predefined Vector3 offset of (2, 0, 4) and let's say my target position is just 0,0,0 depending on the direction of my object relative to the target position, the final position needs to be calculated using my predefined offset from the target position.

    So for example, if my object is exactly behind the target, then the final position should be (2, 0, -4).

    Note that rotation doesn't need to be taken into consideration. I just need a new position to move to with the original direction from the target position retained. I'm not sure how to do the calculation.

    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;
    }
    

    The triangles are the object I want to move. The dotted line show where they should be based on the predefined object.

    image