Raycast3D的碰撞检测无响应

人工智能 2026-07-09

使用GODOT 4.4,我在尝试用节点状态机来实现一个敌人NPC的 AI,它应该通过Raycast 3D检测来发现玩家。当NPC AI与玩家碰撞时,应该像 AIIdleState 脚本所示那样输出“Player detected”。

然而,当AI与玩家发生碰撞时,并不会输出字符串 "Player detected"。为什么AI没有输出,或没有检测到玩家?

Here is the AIIdleState code:

extends State

class_name AIIdleState

var stateName : String = "AIIdle"

var cR : EnemyTest
var wander_time : float = 0.0
var player_detected : bool = false

@onready var raycast: RayCast3D = $"../../RayCast3D"
@export var target: Vector3

func wander():
    #generate a random point around the character within a certain radius
    var random_direction = Vector3(randf_range(-1, 1), 0, randf_range(-1, 1)).normalized()
    target = random_direction
    wander_time = randf_range(2.0, 5.0) #wander for a random time between 2 and 5 seconds

    print("wandered to : ", target)

func enter(char_Ref : CharacterBody3D):
    print("idle")
    cR = char_Ref
    if raycast and cR:
        raycast.add_exception(cR)

func update(delta : float):
    if wander_time <= 0.0:
        wander()
    else:
        wander_time -= delta

func physics_update(delta: float):
    if cR:
        #move towards the target
        cR.velocity = lerp(cR.velocity, target * cR.speed, 0.1)
        #rotate towards the target
        cR.rotation.y = lerp(cR.rotation.y, atan2(target.x, target.z), 0.05)

    playerDetection()

    transition()

func transition():
    if player_detected == true:
        transitioned.emit(self, "AICombat")

func playerDetection():
    if raycast.is_colliding():
        if raycast.get_collider().is_in_group("Player"):
            print("Player detected")
            player_detected = true

This is how the node tree goes:

Enemy AI node tree image

解决方案

I fix it by checking the collision layer of the player, and change the collision layer for the Raycast3D into the same as the player's

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章