UnityAPI学习之碰撞检测与触发检测

碰撞检测

发生碰撞检测的前提:

  1. 碰撞的物体需要有Rigidbody组件和boxcllidder组件

  2. 被碰撞的物体需要有boxcollider组件

示例1:被碰撞的物体拥有Rigidbody组件

两个物体会因为都具有刚体的组件而发生力的作用,如下图所示,当被碰撞的物体被碰撞时,两物体的刚体组件(Rigidbody组件)发生力的作用,从而达到gris(3)推着gris(1)向左移动的效果

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NO18_Collider : MonoBehaviour
{
    public float speed;
    private void Update()
    {
        transform.Translate(Vector2.left * speed * Time.deltaTime,Space.World);
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        print("碰撞的物体为" + collision.gameObject.name);
    }

}

示例2:被碰撞的物体没有Rigidbody组件

被碰撞的物体没有刚体组件(Rigidbody组件),因此gris(3)不会推着gris(1)向左移动

触发检测

发生触发检测的前提:

  1. 碰撞的物体需要有Rigidbody组件和boxcllidder组件

  2. 被碰撞的物体需要有boxcollider组件并勾选IsTrigger选项

示例:

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NO18_Collider : MonoBehaviour
{
    public float speed;
    private void Update()
    {
        transform.Translate(Vector2.left * speed * Time.deltaTime,Space.World);
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        print("碰撞的物体为" + collision.gameObject.name);
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        print(collision.gameObject.name + "进入了");
    }
    private void OnTriggerStay2D(Collider2D collision)
    {
        print(collision.gameObject.name + "停留");
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
        print(collision.gameObject.name + "走出了");
    }
}
相关推荐
XIAOHEZIcode12 小时前
Linux系统鼠标偏移常见原因以及修复方案
linux·运维·游戏
唐青枫1 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Aloys_Code1 天前
逆向一个被遗忘的DVD游戏格式:从DES加密到Rust模拟器
游戏·模拟器·retroarch·复古游戏·native32·sunplus·赤刃·钢铁风暴
金銀銅鐵2 天前
用 Python 实现 Take-Away 游戏
python·游戏
Artech2 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
金銀銅鐵2 天前
用 Pygame 实现 15 puzzle
python·数学·游戏
Scout-leaf3 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6253 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech3 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
通信小呆呆4 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人