Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extends CharacterBody3D
- enum {
- SLEEP,
- AWAKE,
- CHASE,
- ATTACK,
- WAIT
- }
- var CURRENT_STATE = SLEEP
- var cooldown = []
- var stats = {
- "max_health": 100,
- "health": 100,
- "default_speed": 4.0,
- "speed": 0.0,
- "attack_speed": 20.0
- }
- @onready var agent = $NavigationAgent3D
- @onready var plr = get_node(PLAYER_PATH)
- @onready var anim = $Anim
- func _ready():
- stats["speed"] = stats["default_speed"]
- $Indicator.visible = false
- func _physics_process(delta):
- if CURRENT_STATE == CHASE or CURRENT_STATE == ATTACK:
- var next_location = agent.get_next_path_position()
- var final_velocity = (next_location - global_transform.origin).normalized() * stats["speed"]
- agent.set_velocity(final_velocity)
- if CURRENT_STATE == SLEEP: $Sight/Raycasts.look_at(plr.position, Vector3.UP);
- state_handler()
- func awaken():
- if cooldown.has("awake") == true: return
- cooldown.append("awake")
- $Indicator.visible = true
- anim.play("Shock")
- await get_tree().create_timer(0.6).timeout
- $Indicator.visible = false
- CURRENT_STATE = CHASE
- func attack():
- cooldown.append("attack_cd")
- anim.play("Attack")
- stats["speed"] = stats["attack_speed"]
- await get_tree().create_timer(0.4).timeout
- CURRENT_STATE = WAIT
- stats["speed"] = stats["default_speed"]
- await get_tree().create_timer(0.4).timeout
- cooldown.erase("attack_cd")
- CURRENT_STATE = CHASE
- func state_handler():
- match CURRENT_STATE:
- SLEEP:
- stats["speed"] = 0
- anim.play("Sleep")
- if check_in_range() == true:
- CURRENT_STATE = AWAKE
- AWAKE:
- awaken()
- CHASE:
- stats["speed"] = stats["default_speed"]
- anim.play("Run")
- agent.set_target_position(plr.position)
- WAIT:
- anim.play("Shock")
- stats["speed"] = 0
- ATTACK:
- if not cooldown.has("attack_cd"):
- attack()
- func check_in_range():
- for ray in $Sight/Raycasts.get_children():
- if ray.is_colliding():
- var obj = ray.get_collider()
- if obj.name == "PLAYER NAME OR GROUP HERE":
- return true
- else:
- return false
- # In range
- func _on_navigation_agent_3d_target_reached():
- CURRENT_STATE = ATTACK
- func set_float():
- if CURRENT_STATE == ATTACK: return 1
- else: return 0.5
- func _on_navigation_agent_3d_velocity_computed(safe_velocity):
- velocity = velocity.move_toward(safe_velocity, set_float())
- move_and_slide()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement