Godot 4 敌人跟随AI开发求助:GDScript移动逻辑问题
敌人跟随AI在Godot 4中的实现问题
我是编程新手,尤其不熟悉GDScript,正尝试实现一个简易基础的敌人跟随AI,但找到的相关脚本大多基于Godot 3。在Godot 3中可以使用带参数的move_and_slide(direction * speed),但Godot 4中该用法已改变,我找不到解决办法。
以下是我的代码:
extends CharacterBody2D const speed = 35 var dir: Vector2 var isBatChase: bool var player_position var target_position @onready var player = get_parent().get_node("CharacterBody2D") func _physics_process(delta): player_position = player.position target_position = (player_position - position).normalized() func _ready(): isBatChase = true func _process(delta): move(delta) handleAnimation() func move(delta): if isBatChase == true: if position.distance_to(player_position) > 1: velocity = position.direction_to(player_position) * speed * delta if isBatChase == false: velocity += dir * speed * delta move_and_slide() func _on_direction_timer_timeout(): $DirectionTimer.wait_time = choose([1.0, 1.5, 2.0]) if isBatChase == false: dir = choose([Vector2.RIGHT, Vector2.LEFT, Vector2.UP, Vector2.DOWN]) func handleAnimation(): var animatedSprite = $AnimatedSprite2D animatedSprite.play("flying") if dir.x == 1: animatedSprite.flip_h = true elif dir.x == -1: animatedSprite.flip_h = false func choose(array): array.shuffle() return array.front()
我的场景结构:
- 敌人根节点:CharacterBody2D
- 子节点:AnimatedSprite2D(负责播放飞行动画)
- 子节点:DirectionTimer(Timer类型,用于切换巡逻方向)
- 玩家节点:CharacterBody2D(与敌人节点处于同一层级)
内容的提问来源于stack exchange,提问作者Egor Krutsch
相关产品推荐
相关产品推荐

