Search code examples
c#unity-game-enginegame-physics

with AddForceAtPosition objects only moves but doesn't torque


assume that there is a hole that's able to grab all the objects around of itself by its own gravity the script works fine but objects doesn't torque.

i want to make objects move to position of the hole and give them torque while they moving

you can use of two cube one of them could be hole and another one would be block that has rigidbody and box layer

thanks in advance.

public class EatTheBoxes : MonoBehaviour

{

    public bool Starttoeat;
    public float distance,speed,Gizmo_hight,FollowSpeed;
    public LayerMask layerint;
    public ForceMode forcemode;
    private int _numberoftile;






    void FixedUpdate()

    {
       if (Starttoeat)

       {
           CatchTheBoxes(transform.position,distance,layerint);


       }



    }

    void CatchTheBoxes(Vector3 center, float radius , LayerMask layerint)

    {
        Collider[] hitColliders = Physics.OverlapSphere(center, radius,layerint);

        int i = 0;

        while (i < hitColliders.Length)

        {


            Vector3 forceDirection = transform.position -  hitColliders[i].transform.position;

            if (hitColliders[i].CompareTag("bomb"))

            {   
                hitColliders[i].GetComponent<Rigidbody>().AddForceAtPosition(Time.fixedTime * 20 * forceDirection.normalized,transform.position,forcemode);
                hitColliders[i].GetComponent<Rigidbody>().isKinematic = false;

            }

            else

            {



              hitColliders[i].GetComponent<Rigidbody>().AddForceAtPosition(Time.fixedTime * speed * forceDirection.normalized,transform.position,forcemode);

              hitColliders[i].GetComponent<Rigidbody>().isKinematic = false;

            }

            i++;
        }

    }


    void OnDrawGizmos()

    {
        Vector3 newTransform = transform.position;
        newTransform.y = newTransform.y + Gizmo_hight;
        Gizmos.DrawWireSphere(newTransform,distance);
    }
}

Solution

  • You can add torque to rigidbody.

    Just use

    hitColliders[i].GetComponent<Rigidbody>().AddTorque(torqueVector);
    

    Also consider cashing rigidbody:

    Rigidbody hitRigidbody = hitColliders[i].GetComponent<Rigidbody>();
    hitRigidbody.isKinematic = false;
    hitRigidbody.AddForceAtPosition(Time.fixedTime * speed * forceDirection.normalized,transform.position,forcemode);
    hitRigidbody.AddTorque(torqueVector);