Untitled
unknown
plain_text
2 years ago
1.7 kB
5
Indexable
extends CharacterBody2D var speed = 40 var follow_distance = 300 var player_follow = false var player = null var current_dir = "none" var last_dir = "down" var animated_sprite var linear_velocity = Vector2.ZERO func _ready(): animated_sprite = get_node("AnimatedSprite2D") func _physics_process(delta): if player_follow: follow_player(delta) linear_velocity = velocity move_and_slide() update_animation() else: animated_sprite.play("idle_" + last_dir) func follow_player(delta): var distance = global_position.distance_to(player.global_position) if distance <= follow_distance: velocity = (player.global_position - global_position).normalized() * speed print(distance, velocity) # add this line to print the distance and velocity else: velocity = Vector2.ZERO animated_sprite.play("idle_" + last_dir) print(distance, velocity) # add this line to print the distance and velocity func update_animation(): var new_dir = "down" if abs(velocity.y) > abs(velocity.x): if velocity.y < 0: new_dir = "up" elif velocity.y > 0: new_dir = "down" else: if velocity.x < 0: new_dir = "left" elif velocity.x > 0: new_dir = "right" if new_dir != current_dir: current_dir = new_dir last_dir = current_dir animated_sprite.play("walk_" + current_dir) elif velocity == Vector2.ZERO: animated_sprite.play("idle_" + last_dir) func _on_detectionarea_body_entered(body): if body.is_in_group("player"): player = body player_follow = true set_physics_process(true) print("Following player") func _on_detectionarea_body_exited(body): if body.is_in_group("player"): player = null player_follow = false set_physics_process(false) print("Not following player")
Editor is loading...