简体   繁体   English

“oncollisionenter”中的 Rigidbody.Addforce 未在统一 c# 中执行

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

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当我试图制作一个游戏时,当球员与球碰撞时球员踢球并且当我按下 Q 但它不起作用并且没有显示任何错误

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

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.旁注:我猜这是在你的播放器上,所以也许你也可以试试这个:请记住,“if”语句只是为了防止球 object 有不同的扩展名,或者可能是“球(克隆)“ ETC。

Rigidbody rb;
void Start(){
     rb = gameObject.GetComponent<Rigidbody>();
}
void OnTriggerEnter(Collision col){
     if(col.gameObject.name.ToString().Contains("ball") && 
        Input.GetkeyDown(KeyCode.Q)) // this is comp expensive
     {
        //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); //REALLY EXPENSIVE
     }
}

This should give you a step in a different direction, Hopefully, this helps!这应该让您朝着不同的方向迈出一步,希望这会有所帮助! Cheers!干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM