july-game/scripts/player.gd

90 lines
2.5 KiB
GDScript

class_name Player extends CharacterBody2D
@onready var scene_manager: SceneManager = %SceneManager
@onready var right_cast: RayCast2D = $RightCast
@onready var left_cast: RayCast2D = $LeftCast
@onready var right_spawn: Node2D = $RightSpawn
@onready var left_spawn: Node2D = $LeftSpawn
const SHOVE_STRENGTH = 700
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
var direction: float
enum FaceDirection{LEFT, RIGHT}
var facing: FaceDirection = FaceDirection.RIGHT
var pushTarget
func _physics_process(delta: float) -> void:
handle_input()
handle_movement(delta)
move_and_slide()
handle_collisions()
func handle_movement(delta: float):
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
func handle_input():
# Handle jump.
if Input.is_action_just_pressed("ui_accept") 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.
direction = Input.get_axis("ui_left", "ui_right")
if direction > 0:
facing = FaceDirection.RIGHT
elif direction < 0:
facing = FaceDirection.LEFT
var is_shoving = Input.is_action_just_pressed("shove")
if is_shoving and pushTarget is RigidBody2D:
var shoveDirection: int
match facing:
FaceDirection.RIGHT:
shoveDirection = 1
FaceDirection.LEFT:
shoveDirection = -1
pushTarget.apply_central_impulse(Vector2i(shoveDirection, 0)*SHOVE_STRENGTH)
var is_shooting = Input.is_action_just_pressed("shoot")
if is_shooting:
match facing:
FaceDirection.RIGHT:
scene_manager.make_bullet(right_spawn.global_transform, SPEED)
FaceDirection.LEFT:
scene_manager.make_bullet(left_spawn.global_transform, -1*SPEED)
func handle_collisions():
for i in get_slide_collision_count():
var collision := get_slide_collision(i)
var collider := collision.get_collider()
if collider is RigidBody2D:
collider.apply_central_impulse(-collision.get_normal()*100)
if right_cast.is_colliding() && facing == FaceDirection.RIGHT:
collider = right_cast.get_collider()
if collider is Node and collider.is_in_group("shovable"):
pushTarget = collider
elif left_cast.is_colliding() && facing == FaceDirection.LEFT:
collider = left_cast.get_collider()
if collider is Node and collider.is_in_group("shovable"):
pushTarget = collider
else:
pushTarget = null