简体   繁体   English

我在 Unity 中制作游戏时遇到了 C# 中的 OnCollisionEnter 函数问题

[英]I'm having a problem with the OnCollisionEnter function in C# while making a game in Unity

So I learned that you can use a function called OnCollisionEnter to do different things on gameObjects collisions.所以我了解到你可以使用一个名为OnCollisionEnter的函数来对游戏对象碰撞做不同的事情。 I tried something simple :我尝试了一些简单的事情:

using UnityEngine;

public class Bouncing : MonoBehaviour
{
    void OnCollisionEnter(Collision collisionInfo)
    {
        Debug.Log("text");
    }
}

I have a player with these children - Camera, Player Body and Ground Check.我有一个带着这些孩子的球员 - 相机、球员身体和地面检查。 The Player Body has a capsule collider component (beacuse it's a capsule of course, the collider has the "Is Trigger" option unchecked.). Player Body 有一个胶囊碰撞器组件(因为它当然是一个胶囊,所以碰撞器的“Is Trigger”选项没有被选中。)。 The Bouncer was meant to bounce me about 5 units high (I'll do it sometime, if you have any tutorials or anything that could help me then you can comment it too. :) ) The Bouncer has these components - Rigidbody (it isn't kinematic but uses gravity) and a Box Collider ("Is Trigger" option is unchecked.). Bouncer 的目的是让我反弹大约 5 个单位高(我会在某个时候做,如果你有任何教程或任何可以帮助我的东西,那么你也可以评论它。:))Bouncer 有这些组件 - 刚体(它不是't 运动学但使用重力)和 Box Collider(“Is Trigger”选项未选中。)。

I tried to search help on the Internet, but nothing would work as I would like (beacuse it won't work at all).我试图在 Internet 上搜索帮助,但没有任何方法可以如我所愿(因为它根本不起作用)。

Sorry for my bad English, thanks for your help everyone.抱歉我的英语不好,谢谢大家的帮助。

OnCollisionEnter is an event: Unity calls it when the object (which must have a Rigidbody) collides with any collider. OnCollisionEnter 是一个事件:当对象(必须有一个刚体)与任何碰撞器发生碰撞时,Unity 会调用它。 This event may occur in both objects, the rigidbody and the hit object.这个事件可能发生在两个物体中,刚体和被击中的物体。 In the player, the code could be like this:在播放器中,代码可能是这样的:

void OnCollisionEnter(Collision col){
   if (col.gameObject.tag == "Ball"){
     // a rigidbody tagged as "Ball" hit the player
   }
 }

In the ball, the code is pretty much the same - the only difference is that the col structure contains info about the object hit:在球中,代码几乎相同 - 唯一的区别是 col 结构包含有关对象命中的信息:

void OnCollisionEnter(Collision col){
   if (col.gameObject.tag == "Player"){
     // this rigidbody hit the player
   }
 }

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

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