如何让敌人不从平台上掉下来?

问题描述

目前,我制造的敌人能够在撞墙时“巡逻”一个区域并改变方向。 我想把它们放在浮动平台上而不会掉下来,我该怎么做?

这是让他们在撞墙时改变方向的代码

Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,children: [
    Expanded(
      child: Text(
        "Restaurant Name",),Icon(Icons.bookmark_border_outlined),],);

解决方法

根据 OP 需求,以下是我将如何使用 RayCast2D 进行设置。

首先,RayCast2D 将是 KinematicBody2D 的子元素,我们需要将它放在一边并指向下方。还要确保启用了 RayCast2D。如此处所示:

Godot window screenshot

对于我正在使用的代码:

extends KinematicBody2D

export var gravity:float = 100
var _velocity:Vector2 = Vector2.RIGHT * 100

const FLOOR_NORMAL:Vector2 = Vector2.UP

func _physics_process(delta:float) -> void:
    _velocity.y += gravity * delta
    _velocity.y = move_and_slide(_velocity,FLOOR_NORMAL).y
    if is_on_wall() or (is_on_floor() and !$RayCast2D.is_colliding()):
        _velocity.x *= -1.0
        $RayCast2D.position.x *= -1.0

为了检查洞,我们想验证 RayCast2D 是否NOT 碰撞。如果它正在碰撞,则意味着前方有地板。检查 is_on_floor 是为了避免它在空中改变方向。

此外,我在单个语句中检查两个条件。一是避免重复,二是因为如果有两个检查可以改变方向,而且他们都改变了方向……结果就是没有改变方向!下一帧它将尝试无限地再次改变方向。任何类似的情况都会导致 KinematicBody2D 改变方向。它似乎不会移动。

最后,我在所有检查之前执行 move_and_slide 的原因是,当您调用 is_on_wall 时,is_on_floormove_and_slide 会更新。


这是在可见碰撞形状的情况下运行的游戏(调试选项):

Game recording

如您所见,它在墙上和洞上都会改变方向。