Search code examples
c#unity-game-engine2d

how can i set the position of an object though the average of two other objects then add an offset | unity | c# | 2D


Im making a little project using procedural animation in 2D, to set the y pos for the body of the character, I made it so it finds the average of the y between the two of the target objects for the legs then add some offset. However it gives me these two errors "transform.position assign attempt for 'body' is not valid. Input position is { 1.710000, -Infinity, 0.000000 }." "Invalid worldAABB. Object is too large or too far away from the origin." and sends the character into the ground.

the blue icons are the taget position. they snap to the ground using raycast.

    public GameObject distanceobj2;
    Vector3 distanceobj1pos;
    Vector3 distanceobj2pos;
    Vector3 finalpos;
    public float offset;
   

    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        // sets the vector3 var of the target positions;
        distanceobj1pos = distanceobj1.transform.position;
        distanceobj2pos = distanceobj2.transform.position;
        //sets the position of the body
        finalpos.x = transform.position.x;
        finalpos.y = distanceobj1pos.y += distanceobj2pos.y / 2 + offset;
        finalpos.z = transform.position.z;

        //transforms the body to the position
        transform.position = finalpos;
    } ```

Solution

  • I think you need to just change the finalpos.y assignment to

    finalpos.y = (distanceobj1pos.y + distanceobj2pos.y) / 2 + offset;