Rigidbody.Addforce in"oncollisionenter" is not executing in unity c#

Viewed 169

As I was trying to make a game in which player kick the ball when the player collides with ball and as I press Q but it is not working and not showing any error

public Rigidbody rg;
    
    
    void OnCollisionEnter(Collision col)
    {   
         
            if(col.gameObject.name=="ball")
       { 
          if(Input.GetKeyDown(KeyCode.Q))
          {
            rg.AddForce(100,0,0);
          }
       }
    }
1 Answers

Potentially try to add another sphere collider to the ball, and make that a trigger

then it is a matter of changing :

public Rigidbody rg;

void OnCollisionEnter(Collision col)
{   
     
   if(col.gameObject.name=="ball")
   { 
      if(Input.GetKeyDown(KeyCode.Q))
      {
        rg.AddForce(100,0,0);
      }
   }
}

To :

public Rigidbody rg;

void OnTriggerEnter(Collision col)
{   
     
   if(col.gameObject.name=="ball")
   { 
      if(Input.GetKeyDown(KeyCode.Q))
      {
        rg.AddForce(100,0,0);
      }
   }
}

The idea is that collision in unity is finicky, so your best bet is just to have a larger trigger to detect if the player is within range of the ball

Side NOTE : I'm guessing that this is on your player, so maybe you could try this as well : keep in mind that the "if" statement is just in case the ball object has different name extensions, or maybe "ball (clone)" etc.

Rigidbody rb;
void Start(){
     rb = gameObject.GetComponent<Rigidbody>();
}
void OnTriggerEnter(Collision col){
     if(col.gameObject.name.ToString().Contains("ball") && 
        Input.GetkeyDown(KeyCode.Q))
     {
        //here you can add force to the player, or to the ball
        // for the player : 
        rb.AddForce(100,0,0);
        // for the ball
        col.GetComponent<Rigidbody>().AddForce(100,0,0);
     }
}

This should give you a step in a different direction, Hopefully, this helps! Cheers!

Related