april-2025/scripts/player.gd

79 lines
2.2 KiB
GDScript

class_name Player extends CharacterBody2D
@onready var ray_cast_2d: RayCast2D = $RayCast2D
@onready var game: GameController = $".."
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
const PUSH = 100.0
enum InteractionStates {NONE, ATTRACT, REPEL}
var interactionState = InteractionStates.NONE
func _physics_process(delta: float) -> void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
handle_input()
move_and_slide()
handle_collisions()
func handle_input() -> void:
# Handle jump.
if Input.is_action_just_pressed("ui_up") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction := Input.get_axis("ui_left", "ui_right")
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
# Follow mouse cursor with raycast.
var target = get_local_mouse_position()
ray_cast_2d.target_position = target
# Handle attract/repel inputs, or reset to no interaction
if Input.is_action_just_pressed("attract"):
interactionState = InteractionStates.ATTRACT
#elif Input.is_action_just_pressed("repel"):
#interactionState = InteractionStates.REPEL
else:
interactionState = InteractionStates.NONE
# Shoot bullets
if Input.is_action_just_pressed("shoot"):
var dir = (get_global_mouse_position() - global_position).normalized()
%SceneManager.makeBullet(global_position, dir)
func update_movement() -> void:
pass
func update_states() -> void:
pass
func handle_collisions() -> void:
#for i in get_slide_collision_count():
#var c = get_slide_collision(i)
#if c.get_collider() is RigidBody2D:
#c.get_collider().apply_central_impulse(-c.get_normal() * PUSH)
if ray_cast_2d.is_colliding():
var collider = ray_cast_2d.get_collider()
if collider is RigidBody2D:
var angle = collider.get_angle_to(to_local(position))
var direction = Vector2.RIGHT.rotated(angle)
match interactionState:
InteractionStates.REPEL:
collider.apply_central_impulse(direction * PUSH)
InteractionStates.ATTRACT:
collider.apply_central_impulse((direction * PUSH) * -1)
InteractionStates.NONE:
pass