简体   繁体   English

unity C# 碰撞

[英]Unity C# Collision

How do I create a script for collision detection between two object.如何为两个对象之间的碰撞检测创建脚本。 Here is my code:这是我的代码:

using UnityEngine;

public class PlayerCollision : MonoBehaviour
{
    public PlayerMovement movement;

    void OnCollisionEnter (Collision collisionInfo)
    {
        if (collisionInfo.collider.tag == "Obstacle")
        {
            movement.enabled = false;
        }
    }
}

Judging by https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html , there's nothing wrong with the code that you've written.https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html来看,您编写的代码没有任何问题。

A common reason that these method usages fail is because of the way you're handling movement (in this case) in your PlayerMovement script.这些方法使用失败的一个常见原因是您在 PlayerMovement 脚本中处理移动的方式(在本例中)。

If you're modifying a transform's position directly through the position property for example, physics operations like collisions are not calculated.例如,如果您直接通过 position 属性修改变换的位置,则不会计算碰撞等物理操作。 https://docs.unity3d.com/ScriptReference/Transform-position.html https://docs.unity3d.com/ScriptReference/Transform-position.html

Another common reason is that you don't have a rigidbody attached to one of the objects, so collision operations do not fire.另一个常见原因是您没有将刚体附加到其中一个对象上,因此不会触发碰撞操作。

See the "Collision action matrix" section here: https://docs.unity3d.com/Manual/CollidersOverview.html请参阅此处的“碰撞行动矩阵”部分: https : //docs.unity3d.com/Manual/CollidersOverview.html

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

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