1
\$\begingroup\$

like pain from naruto, I wanna be able to press a button and be able to push objects

here's my push method

 void DoPush()
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, pushRadius);

        foreach (Collider pushedObject in colliders)
        {
            if (pushedObject.CompareTag("Enemy"))
            {
                Rigidbody pushedBody = pushedObject.GetComponent<Rigidbody>();

                pushedBody.AddForce(-transform.forward * 500, ForceMode.Force);
           
            }
        }
     
    }

the problem with this method is when I go behind the objects I push, they go towards me

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You are pushing your object in the reverse direction you are facing.

Try:

void DoPush()
{
    Collider[] colliders = Physics.OverlapSphere(transform.position, pushRadius);

    foreach (Collider pushedObject in colliders)
    {
        if (pushedObject.CompareTag("Enemy"))
        {
            Rigidbody pushedBody = pushedObject.GetComponent<Rigidbody>();

            // Get direction from your postion toward the object you wish to push
            var direction = pushedBody.transform.position - transform.position;

            // Normalization is important, to have constant unit!
            pushedBody.AddForce(direction.normalized * 500, ForceMode.Force);
       
        }
    }
 
}
\$\endgroup\$
2
  • \$\begingroup\$ Thank you so much! I appreciate it! \$\endgroup\$
    – XXdaimon
    May 4, 2021 at 23:12
  • \$\begingroup\$ @XXdaimon No problem :) Please consider marking my answer as solution via checkmark next to it \$\endgroup\$
    – PiotrK
    May 5, 2021 at 8:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .