Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

使用 Area2D

前言

Godot提供了许多碰撞对象来提供碰撞检测和响应. 试图决定为你的项目使用哪一个可能会让人感到困惑. 如果你了解它们各自的工作原理以及它们的优点和缺点, 你就可以避免问题并简化开发. 在本教程中, 我们将查看 Area2D 节点, 并展示一些如何使用它的例子.

备注

本文假设你熟悉 Godot 中的各种物理体,否则请先阅读 物理介绍

什么是区域?

Area2D定义了二维空间的区域. 在这个空间中, 你可以检测到其他 CollisionObject2D 节点的重叠, 进入和退出. 区域(Area)还允许覆盖本地物理属性. 我们将在下面讨论这些功能中的每一个.

Area 的属性

区域有许多属性可用于自定义它们的行为.

../../_images/area2d_properties.webp

The Gravity, Linear Damp, and Angular Damp sections are used to configure the area's physics override behavior. We'll look at how to use those in the Area influence section below.

MonitoringMonitorable 用于启用和禁用该区域。

The Audio Bus section allows you to override audio in the area, for example to apply an audio effect when the player moves through.

Note that Area2D extends CollisionObject2D, so it also provides properties inherited from that class. The Collision section of CollisionObject2D is where you configure the area's collision layer(s) and mask(s).

重叠检测

也许Area2D节点最常见的用途是用于触碰和重叠检测. 当需要知道两个物体已经触碰, 但不需要物理碰撞时, 可以使用一个区域来通知.

例如, 要做一个硬币让玩家去捡. 硬币并不是一个实心的物体, 玩家不能站在上面, 也不能推它, 只是想让它在玩家触碰它的时候消失.

这是硬币节点的设置:

../../_images/area2d_coin_nodes.webp

To detect the overlap, we'll connect the appropriate signal on the Area2D. Which signal to use depends on the player's node type. If the player is another area, use area_entered. However, let's assume our player is a CharacterBody2D (and therefore a CollisionObject2D type), so we'll connect the body_entered signal.

备注

如果熟悉使用信号, 请参阅 使用信号 的介绍.

extends Area2D

func _on_coin_body_entered(body):
    queue_free()

现在我们的游戏角色可以收集硬币了!

其他一些使用实例:

  • 区域对于子弹和其他弹丸物体来说是非常好用, 它可以击中并造成伤害, 但不需要其他物理效果, 如弹跳.

  • 用敌人周围的一个大圆圈区域设定为 "探测" 半径, 当玩家在该区域外时, 敌人就无法 "看到" 玩家.

  • "安保摄像头" - 在有多个摄像头的大型关卡中, 在每个摄像头上附加区域(area), 并在玩家进入时激活它们.

游戏中使用 Area2D 的示例请参阅 你的第一个 2D 游戏

区域影响

区域节点的第二个主要用途是改变物理效果。默认情况下,区域不会这样做,但你可以用 空间覆盖(Space Override) 属性启用这个功能。当区域重叠时,它们会按照 优先级(Priority) 的顺序进行处理(优先级较高的区域会被优先处理)。覆盖有四个选项:

  • 合并(Combine) - 该区域将其数值加到目前已计算的数值上.

  • 替换(Replace) - 该区域替换物理属性, 低优先级区域被忽略.

  • 合并-替换 (Combine-Replace) - 该区域将其重力/阻尼值加到目前为止计算出的所有数值上(按优先顺序), 忽略任何较低优先级的区域.

  • 替换-合并 (Replace-Combine) - 该区域替换了目前为止计算的所有重力或阻尼, 但继续计算其余区域.

使用这些属性, 可以创建具有多个重叠区域的复杂行为.

可以重写的物理属性有:

  • 重力(Gravity) - 区域内的重力强度.

  • 重力方向 (Gravity Direction) - 此向量不需要归一化。

  • 线性阻尼 (Linear Damp) - 物体停止移动的速度-每秒损失的线速度.

  • 角度阻尼 (Angular Damp) - 物体停止旋转的速度-每秒损失的角速度.

重力点

The Gravity Point property allows you to create an "attractor". Gravity in the area will be calculated towards a point, given by the Point Center property. Values are relative to the Area2D, so for example using (0, 0) will attract objects to the center of the area.

示例

以下所附中的示例项目包含三个区域, 它们说明了物理重写.

../../_images/area2d_override.gif

You can download this project here: area_2d_starter.zip