extends CharacterBody2D @export var id: int = 1 @export var max_speed: float = 90 @onready var sprite: AnimatedSprite2D = $AnimatedSprite2D var is_hitting: bool = false var was_moving: bool = false var anim_dir: String var def_dir: String func _ready() -> void: assert(id == 1 or id == 2, "id ("+str(id)+") is invalid") anim_dir = 'up' if id == 1 else 'down' def_dir = 'up' if id == 1 else 'down' sprite.play(def_dir) sprite.frame = 1 sprite.pause() func _physics_process(_delta: float) -> void: var movement_vector: Vector2 = get_movement_vector() var direction: Vector2 = movement_vector.normalized() if not is_hitting else Vector2.ZERO velocity = direction * max_speed move_and_slide() var is_moving: bool = velocity.length() > 10 if Input.is_action_pressed("hit_left") and not is_hitting: hit("left") elif Input.is_action_pressed("hit_right") and not is_hitting: hit("right") if is_moving and not is_hitting: if abs(velocity.x) > abs(velocity.y): anim_dir = 'right' if velocity.x > 0 else 'left' else: anim_dir = 'down' if velocity.y > 0 else 'up' sprite.play(anim_dir) else: if was_moving and not is_hitting: sprite.play(def_dir) sprite.frame = 1 sprite.pause() was_moving = is_moving func get_movement_vector() -> Vector2: var x_mov: float = Input.get_action_strength('move_right') - Input.get_action_strength('move_left') var y_mov: float = Input.get_action_strength('move_down') - Input.get_action_strength('move_up') return Vector2(x_mov, y_mov) func hit(dir: String) -> void: if not is_hitting: sprite.play('up' if id == 1 else 'down') sprite.frame = 1 sprite.pause() var sprite_texture: Texture2D = sprite.sprite_frames.get_frame_texture('up', 1) var hit_node: Area2D = preload("res://scenes/hit/hit.tscn").instantiate() # flip entire node horizontally if spawning left # flip vertically if player 2 hit_node.scale = Vector2( -1 if dir == "left" else 1, 1 if id == 1 else -1 ) add_child(hit_node) # set position according to frame width and height @warning_ignore("integer_division") hit_node.global_position = global_position + Vector2( (sprite_texture.get_width()/2)*(-1 if dir == "left" else 1), (sprite_texture.get_height()*-1) if id == 1 else 4 ) hit_node.timer.connect("timeout", _on_hit_end) is_hitting = true func _on_hit_end() -> void: is_hitting = false