首页 > 解决方案 > OnCollisonEnter(Collision other) 没有检测到我的对象?

问题描述

我正在 Unity VR 中制作一款游戏,我在其中打数字并获得分数。

截屏

手套负责检测它们击中的数字之间的碰撞。在我的手套上,我有一个PunchScript组件,每个数字都有一个rigidBodycollider

问题是似乎从来没有发生过碰撞。我在碰撞检测代码中放置了一个Debug.LogError来断言这一点。

我尝试打开/关闭所有对象的运动学并使用不同的碰撞系统无济于事。

这是我的PunchScript组件:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PunchScript : MonoBehaviour
{
    public SteamVR_TrackedObject hand; 
    private Rigidbody rBody;
    private bool visible = true;

    // Start is called before the first frame update
    void Start()
    {
        rBody = GetComponent<Rigidbody>();  
    }

    // Update is called once per frame
    void Update()
    {
        rBody.MovePosition(hand.transform.position);
        rBody.MoveRotation(hand.transform.rotation);

       // print(rBody.velocity.magnitude* 1000);
    }

    void OnCollisonEnter(Collision other) 
    {
        Rigidbody otherR = other.gameObject.GetComponentInChildren<Rigidbody>();

        if (other.gameObject.name == "frpnchbg") {
            Debug.LogError("Hit!");
        }

        if (other == null)
            return;

        Vector3 avgPoint = Vector3.zero;

        foreach (ContactPoint p in other.contacts) {
            avgPoint += p.point;
        }

        avgPoint /= other.contacts.Length;

        Vector3 dir = (avgPoint - transform.position).normalized;
        otherR.AddForceAtPosition(dir *50f* rBody.velocity.magnitude, avgPoint);
    }
}

这是手套对象在 Unity 检查器中的外观。

统一检查员

标签: c#unity3d

解决方案


正确编写 Unity 回调方法的名称非常重要,否则 Unity 将无法在对象上检测到它们(并因此永远无法执行它们)。

在您的情况下,您拼错了OnCollisionEnter回调。而不是OnCollisonEnter应该是OnCollisionEnter.


推荐阅读