碰撞检测功能在游戏开发里是比较常用的,比如地图上无法穿越的部分,以及对于敌人的攻击判定等等。这篇博客就开简单介绍一下碰撞事件的处理。
参考视频:Unity碰撞检测_哔哩哔哩_bilibili

首先,我们需要为想要进行碰撞检测的对象添加上图中绿色框中的两个组件,分别是 刚体2D 以及 盒子碰撞检测器。
其中 盒子碰撞检测器 中的触发按钮需要勾选。

当我们添加完上述的组件后,就需要编写脚本处理碰撞事件了,主要有下面的三个函数。

当我们在脚本中调用上面的三个函数就可以检测到碰撞了。
我们给敌人对象也设置一个 盒子碰撞检测器,然后再角色对象脚本中加入碰撞检测,具体的代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class PlayerController : MonoBehaviour
{// 人物移动的速度public float speed = 5;// 获取移动指令变量public float moveX;public float moveY;// 获取角色的动画器Animator animator;// 获取角色的刚体组件Rigidbody2D rd2d;// 动画器变量名string PlayerState = "PlayerState";// 角色状态表enum CharState{idle = 0,walk = 1,attack = 2}// Start is called before the first frame updatevoid Start(){// 获取动画器animator = GetComponent<Animator>();// 获取刚体组件rd2d = GetComponent<Rigidbody2D>();}// Update is called once per framevoid Update(){}void FixedUpdate(){// 首先判断是否移动// 获取x轴和y轴的移动指令// 获取水平方向指令moveX = Input.GetAxisRaw("Horizontal");// 获取垂直方向指令moveY = Input.GetAxisRaw("Vertical");// 获取人物的位置信息Vector2 p = transform.position;p.x = p.x + moveX * speed * Time.deltaTime;p.y = p.y + moveY * speed * Time.deltaTime;// 将新坐标赋值给物体位置管理属性transform.position = p;/*// 刚体的速度Vector2 movement = new Vector2();movement.x = moveX;movement.y = moveY;movement.Normalize();rd2d.velocity = movement * speed;*/// 如果有移动就改变动画if (moveX != 0 || moveY != 0){// 给动画器变量赋值animator.SetInteger(PlayerState, (int)CharState.walk);Debug.Log(animator.GetInteger(PlayerState));} else{animator.SetInteger(PlayerState, (int)CharState.idle);Debug.Log(animator.GetInteger(PlayerState));}// 然后判断是否按下了其他键if (Input.GetKey(KeyCode.K)){animator.SetInteger(PlayerState, (int)CharState.attack);Debug.Log(animator.GetInteger(PlayerState));}}/*void OnCollisionEnter(){Debug.Log("撞到啦...OnCollisionEnter");}*/// 碰撞检测函数,进入的时候执行void OnTriggerEnter2D(Collider2D collider){Debug.Log("撞到啦...");Debug.Log(collider.gameObject.tag);}//// 停留的时候执行void OnTriggerStay2D(Collider2D collider){Debug.Log("一直停留在碰撞状态...");}// 退出的时候执行void OnTriggerExit2D(Collider2D collider){Debug.Log("退出碰撞状态...");}}
然后我们运行游戏,移动人物到敌人的地方就可以在控制台看到程序检测出碰撞了。














![[12]机器学习_smote算法](https://img-blog.csdnimg.cn/83d6c9cccbce4f6fa9e690046559280f.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5pep5bed5qmZ,size_20,color_FFFFFF,t_70,g_se,x_16)

