Unity:使用onCollisionEnter检测碰撞

本文介绍了如何在Unity中使用C#脚本检测和响应两个游戏对象之间的碰撞,包括添加Box Collider、游戏标签的使用,以及通过Unity控制台输出自定义消息。此外,还提供了一个实践练习,教你创建多个目标,每个目标被击中时显示不同的消息。
摘要由CSDN通过智能技术生成

In this tutorial, we'll learn how to detect collisions between two gameObjects using a simple C# script, and how to execute some code when the objects collide.

在本教程中,我们将学习如何使用简单的C#脚本检测两个gameObject之间的碰撞,以及当对象碰撞时如何执行一些代码。

We'll also learn how to work with game tags and why they're important, and we'll also learn how to use Unity's console to output customized messages that can come handy to us as developers and testers.

我们还将学习如何使用游戏标签,以及它们为何如此重要,还将学习如何使用Unity的控制台输出自定义消息,这些消息对于开发人员和测试人员而言很方便。

To get started, let's open up the project we've been working on so far:

首先,让我们打开到目前为止我们一直在努力的项目:

Detecting Collisions with onCollisionEnter

Everything seems to be in order. Now, let's add a new 2D Box Collider to our bullet(fireball) so it can detect collisions (Remember, the Collider is what actually defines a collision, not a Rigidbody).

一切似乎井井有条。 现在,让我们向子弹(火球)添加一个新的2D Box Collider ,以便它可以检测到碰撞(请记住, Collider实际上是定义碰撞的对象,而不是Rigidbody )。

Want to see how to add a Collider to a game object? You will find it here.

是否想了解如何将对撞机添加到游戏对象? 您会在这里找到它

Here's a quick question: If we want all generated bullets (fireballs) to have a box collider, what do we modify? The prefab of course. Attach a 2D box collider to the prefab, and that's about it for the bullet.

这是一个快速的问题:如果我们要让所有生成的子弹(火球)都具有盒对撞机,我们要修改什么? 当然是预制的。 将2D盒子对撞机附加到预制件上,这就是子弹头。

Now, let's give our main character something to shoot at. How about a target? We have one around here somewhere.

现在,让我们给主角一些东西。 目标如何? 我们这附近有一个。

Detecting Collisions using colliders

There we go. Let's import this target into our game project and into our scene (You should be fairly comfortable

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值