game1/scripts/Player.gd

93 lines
2.6 KiB
GDScript3
Raw Normal View History

class_name Player extends CharacterBody2D
2025-08-18 02:18:14 +00:00
const bullet_scene = preload("res://Scenes/bullet.tscn")
@onready var right_cast: RayCast2D = $RightCast
@onready var left_cast: RayCast2D = $LeftCast
@onready var bullet_spawn_point_right: Node2D = $BulletSpawnPointRight
@onready var bullet_spawn_point_left: Node2D = $BulletSpawnPointLeft
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
2025-08-18 02:18:14 +00:00
const PUSH_POWER = 2000
var direction: float
enum FaceDirection{LEFT, RIGHT}
var facing: FaceDirection = FaceDirection.RIGHT
var pushTarget: Object
var pushEnabled: bool = false
func _physics_process(delta: float) -> void:
2025-08-18 02:18:14 +00:00
handle_input(delta)
handle_movement(delta)
handle_collisions(delta)
2025-08-18 02:18:14 +00:00
func handle_input(delta: float) -> void:
var dir: int = 0
match facing:
FaceDirection.LEFT:
dir = -1
FaceDirection.RIGHT:
dir = 1
# 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.
2025-08-18 02:18:14 +00:00
direction = Input.get_axis("ui_left", "ui_right")
if direction < 0:
facing = FaceDirection.LEFT
elif direction > 0:
facing = FaceDirection.RIGHT
if Input.is_action_just_pressed("ForcePush") && pushEnabled:
pushTarget.apply_central_impulse(Vector2(dir, 0) * PUSH_POWER)
if Input.is_action_just_pressed("Shoot"):
var spawnAt: Node2D = bullet_spawn_point_left
if dir == 1:
spawnAt = bullet_spawn_point_right
print("make a bullet")
var b = %SCENEMANAGER.makeBullet(spawnAt.global_transform, dir)
func handle_movement(delta: float) -> void:
handle_gravity(delta)
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
2025-08-18 02:18:14 +00:00
func handle_collisions(delta: float) -> 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() * 100)
2025-08-18 02:18:14 +00:00
if right_cast.is_colliding() && facing == FaceDirection.RIGHT:
var col = right_cast.get_collider()
if col != null && col.is_in_group("pushable"):
pushTarget = col
pushEnabled = true
print("right pushable")
elif left_cast.is_colliding() && facing == FaceDirection.LEFT:
var col = left_cast.get_collider()
if col != null && col.is_in_group("pushable"):
pushTarget = col
pushEnabled = true
print("left pushable")
else:
pushEnabled = false
pushTarget = null
func handle_gravity(delta: float) -> void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta