smashball/scenes/player/player.gd
2025-11-14 08:01:06 -03:00

76 lines
2.1 KiB
GDScript

extends CharacterBody2D
@export var id: int = 1
@export var max_speed: float = 150
@onready var sprite: AnimatedSprite2D = $AnimatedSprite2D
var is_hitting: bool = false
var was_moving: bool = false
var anim_dir: String = 'down'
func _ready() -> void:
sprite.play('down')
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:
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('down')
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')
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
hit_node.scale = Vector2(-1 if dir == "left" else 1, 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
)
hit_node.timer.connect("timeout", _on_hit_end)
is_hitting = true
func _on_hit_end() -> void:
is_hitting = false