繁体   English   中英

Unity3D碰撞检测不起作用

[英]Unity3D collision detection not working

在制作躲避球游戏时,我在使用OnCollisionEnter时遇到困难,那么当用特定颜色的球击打时,有什么方法可以使玩家丧命吗?

我尝试过的

播放器上的脚本:

    void Start () {
    livesText = GameObject.FindWithTag("lives").GetComponent<Text>();
    lives = 4;

}

// Update is called once per frame
void Update () {

    livesText.text = "Lives: " + lives;
}

void OnCollisionEnter(Collision bol)
{
     if (bol.gameObject.name == "blueBall")
    {

      lives = lives - 1;

      Debug.Log("Collided");

      }


}

在此处输入图片说明

在此处输入图片说明

播放器预制:突出显示的部分是播放器的实际身体:

在此处输入图片说明

播放器预制件的故障:

玩家1:

在此处输入图片说明

FPSController:

在此处输入图片说明

FirstPersonCharacter:

在此处输入图片说明

胶囊:

在此处输入图片说明

您可以通过两种方式执行此操作,具体取决于在游戏过程中是生成颜色还是使用已经存在的颜色。

方法1

为每种颜色创建一个标签,然后确保在编辑器中为每个对象分配了标签。 使用CompareTag比较碰撞的颜色。

是有关如何创建标签的快速教程。

void OnCollisionEnter(Collision bol)
{
    if (bol.gameObject.CompareTag("blueBall"))
    {
        lives = lives - 1;
        Debug.Log("Collided red");
    }
    else if (bol.gameObject.CompareTag("greenBall"))
    {
        lives = lives - 2;
        Debug.Log("Collided green");
    }

    else if (bol.gameObject.CompareTag("blackBall"))
    {
        lives = lives - 3;
        Debug.Log("Collided black");
    }
}

方法2

现在,如果要执行高级操作,必须在运行时生成颜色,则必须检查颜色的阈值。 有关于这一个问题在这里 ,我移植的代码统一。

public double ColourDistance(Color32 c1, Color32 c2)
{
    double rmean = (c1.r + c2.r) / 2;
    int r = c1.r - c2.r;
    int g = c1.g - c2.g;
    int b = c1.b - c2.b;
    double weightR = 2 + rmean / 256;
    double weightG = 4.0;
    double weightB = 2 + (255 - rmean) / 256;
    return System.Math.Sqrt(weightR * r * r + weightG * g * g + weightB * b * b);
}

然后在碰撞回调函数中执行以下操作:

void OnCollisionEnter(Collision bol)
{
    MeshRenderer ballMesh = bol.gameObject.GetComponent<MeshRenderer>();

    if (ColourDistance((Color32)ballMesh.sharedMaterial.color, (Color32)Color.red) < 300)
    {
        lives = lives - 1;
        Debug.Log("Collided red");
    }
    else if (ColourDistance((Color32)ballMesh.sharedMaterial.color, (Color32)Color.green) < 300)
    {
        lives = lives - 2;
        Debug.Log("Collided green");
    }

    else if (ColourDistance((Color32)ballMesh.sharedMaterial.color, (Color32)Color.black) < 300)
    {
        lives = lives - 3;
        Debug.Log("Collided black");
    }
}

编辑

由于使用的是第一人称控制器,因此未调用OnCollisionEnter函数。

在这种情况下,必须使用OnControllerColliderHit函数。

void OnControllerColliderHit(ControllerColliderHit bol)
{

}

函数中的所有内容保持不变。

暂无
暂无

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

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