Godot Version
4.4
Im trying to make a character that has 2 “stages” the wandering stage where he just walks around and the chase stage where he chases the player until he exists the out of his line of sight(ray cast for 3 seconds) there are a few problems.:
1-he changes the ray cast mid walk (i dunno why);
2- he gets stuck on walls when it goes agains a wall he just stays there;
3- he doesnt chase. he just goes ignores the player.
i will send below the list of objects the enemy has + the code so if anyone can help me i would appreciate it.
extends CharacterBody2D
@export var player: CharacterBody2D
@export var speed: int=50
@export var Chase_speed: int=150
@export var Accel: int=300
@onready var sprite: AnimatedSprite2D = $AnimatedSprite2D
@onready var raycast: RayCast2D = $AnimatedSprite2D/RayCast2D
@onready var timer: Timer = $Timer
var gravity: float = ProjectSettings.get_setting("physics/2d/default_gravity")
var direction: Vector2
var Right_bound: Vector2
var Left_bound: Vector2
enum States{
Wander,
Chase
}
var current_state =States.Wander
func _ready() -> void:
Left_bound= self.position + Vector2(-125, 0)
Right_bound= self.position + Vector2(125, 0)
func _physics_process(delta: float) -> void:
handle_gravity(delta)
handle_movement(delta)
change_directions()
look_players()
func look_players():
if raycast.is_colliding():
var collider = raycast.get_collider()
if collider == player:
chase_player()
elif current_state == States.Chase:
stop_chase()
elif current_state == States.Chase:
stop_chase()
func chase_player()-> void:
timer.stop()
current_state = States.Chase
func stop_chase()-> void:
if timer.time_left <=0:
timer.start
func handle_movement(delta:float)-> void:
if current_state == States.Wander:
velocity= velocity.move_toward(direction * speed , Accel * delta)
else:
velocity= velocity.move_toward(direction * Chase_speed , Accel * delta)
move_and_slide()
func change_directions()-> void:
if current_state == States.Wander:
if sprite.flip_h:
#moving right
if self.position.x <= Right_bound.x:
direction = Vector2(2,0)
else:
#flip to move left
sprite.flip_h = false
raycast.target_position = Vector2(-125,0)
else:
#moving left
if self.position.x >= Left_bound.x:
direction = Vector2(2,0)
else:
#flip to move right
sprite.flip_h = true
raycast.target_position = Vector2(125,0)
else:
#chase follow player
direction=(player.position - self.position) .normalized()
direction = sign(direction)
if direction.x ==1:
#flip right
sprite.flip_h = true
raycast.target_position = Vector2(125,0)
else:
#flip left
sprite.flip_h = false
raycast.target_position = Vector2(-125,0)
func handle_gravity(delta:float)-> void:
if not is_on_floor():
velocity.y += gravity * delta
func _on_timer_timeout() -> void:
current_state = States.Wander