Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extends KinematicBody
- # Speed of the character in units per second
- export var speed = 3
- # List of points representing the path to follow
- var path = []
- # Current index in the path list
- var cur_path_idx = 0
- # Target position to move towards
- var target = null
- # Current velocity of the character
- var velocity = Vector3.ZERO
- # Distance threshold for reaching a target position
- var threshold = .1
- # Reference to the Navigation node
- onready var nav = get_parent()
- # Reference to the AnimationPlayer node
- onready var animatedSprite = get_node("AnimatedSprite3D")
- func _ready():
- # Wait for the owner and player nodes to be ready
- yield(owner, "ready")
- yield(get_node("../../player"), "ready")
- # Set the target position to the player's global transform origin
- target = get_node("../../player").global_transform.origin
- func _physics_process(delta):
- # Update the character's movement and animation
- update_movement()
- update_animation()
- func update_movement():
- if path.size() > 0:
- # Follow the path if there is one
- move_along_path()
- else:
- # Move towards the target position if there is no path
- move_towards_target()
- func move_along_path():
- if cur_path_idx >= path.size():
- return
- if global_transform.origin.distance_to(path[cur_path_idx]) < threshold:
- # Advance to the next point in the path if the character is close enough
- cur_path_idx += 1
- else:
- # Calculate the direction to the next point in the path
- var direction = path[cur_path_idx] - global_transform.origin
- velocity = direction.normalized() * speed
- move_and_slide(velocity, Vector3.UP)
- func move_towards_target():
- if cur_path_idx >= path.size():
- return
- if global_transform.origin.distance_to(path[cur_path_idx]) < threshold:
- cur_path_idx += 1
- else:
- var direction = path[cur_path_idx] - global_transform.origin
- velocity = direction.normalized() * speed
- move_and_slide(velocity, Vector3.UP)
- func update_animation():
- if velocity.length() > 0:
- # Play the "Walk" animation if the character is moving
- $AnimatedSprite3D.play("walking")
- else:
- # Stop the current animation if the character is not moving
- $AnimatedSprite3D.play("idle")
- func get_target_path(target_pos):
- # Calculate the simple path to the target position
- path = nav.get_simple_path(global_transform.origin, target_pos)
- cur_path_idx = 0
- func _on_Timer_timeout():
- # Update the target position and path every frame
- target = get_node("../../player").global_transform.origin
- get_target_path(target.global_transform.origin)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement