Clean up player.gd: names, comments, grouping, smaller _physics_process #6

Merged
SnekInAScarf merged 1 commit from player-cleanup into main 2026-10-31 20:47:46 -05:00

View file

@ -1,12 +1,10 @@
extends CharacterBody2D
# Note: should check if i want unsticking to occur while moving on ceiling or wall.
# so far it isn't the case with ground movement.
const GROUND_SPEED = 150.0
# ---- Movement ----
# All speeds are positive amounts; the direction is applied where they're used.
const GROUND_SPEED = 150.0 # Crawling speed on floors, walls and ceilings.
const AIR_SPEED = 75.0
const CLIMB_SPEED = -150.0
const CLIMB_SPEED = 150.0 # Up and down a wall.
# Acceleration on floors, walls and ceilings. Full speed in 4 frames, stopped in 6.
const GROUND_ACCEL = GROUND_SPEED / (4.0 / 60.0)
@ -16,15 +14,93 @@ const GROUND_FRICTION = GROUND_SPEED / (6.0 / 60.0)
const AIR_ACCEL = 600.0
const AIR_DRAG = 300.0
const MAX_FALL_SPEED = 400.0
# ---- Sticking to walls and ceilings ----
const CEILING_STICK_SPEED = 20.0 # Small push up that keeps the slime pressed against the ceiling.
const WALL_STICK_SPEED = 20.0 # Small push into the wall that keeps the slime pressed against it.
# How far we'll pull back onto a wall/ceiling we're sticking to if we drift off it.
const SURFACE_SNAP_DISTANCE = 4.0
# How long to hold a direction before something happens: letting go of a wall
# or ceiling (holding away from it), carrying on over an edge we're holding at,
# hopping, and how long we hang on a lip.
const HOLD_TIME = 0.5
const ROTATE_TO_WALL_SPEED = 25 # How quickly to rotate the sprite when clinging to a wall.
const CEILING_STICK_SPEED = -20.0 # Small upward push that keeps the slime pressed against the ceiling.
const WALL_STICK_SPEED = 20.0 # Small push into the wall that keeps the slime pressed against it.
var isStickingToWall := false
var wallNormalX := 0.0 # Which way the wall we're on faces (-1 left, 1 right).
var timeSpentUnstickingWall := 0.0
var isStickingToCeiling := false
var timeSpentUnstickingCeiling := 0.0
# Right after wrapping onto a wall we're usually still holding away from it,
# so don't count that towards unsticking until the direction is released.
var ignoreWallUnstickUntilRelease := false
# Same for down after wrapping onto a ceiling (e.g. crawling down a wall and under).
var ignoreCeilingUnstickUntilRelease := false
# Temp for now, need to use aniamtedspite2d later on
@onready var sprite = $Sprite2D
# ---- Surface edges ----
# The edge sensors are rotated to point into whatever surface we're on, a
# little way to each side of us. If one stops touching the surface, there's an
# edge within edgeSensorRange on that side, and pressing into the surface will
# wrap over it onto the side of the platform.
@export var edgeSensorRange := 12.0
const EDGE_SENSOR_DEPTH = 4.0 # How far past our radius the sensors reach into the surface.
var wallFacingY := -1.0 # Which way we last moved along a wall (-1 is up).
# Holding at an edge: moving along a surface towards its edge stops at the edge,
# and only carries on over it after holding towards it for HOLD_TIME.
var timeSpentHoldingEdge := 0.0
# ---- Edge wrapping ----
# Instead of relying on physics to slide around a corner, the slime swings
# around it on a quarter circle so it always feels the same.
const WRAP_MARGIN = 0.5 # Extra gap from the corner so we don't clip into it.
var isWrapping := false
var wrapCorner := Vector2.ZERO
var wrapEntryStart := Vector2.ZERO # Where a straight move before the arc starts from.
var wrapEntryLength := 0.0
var wrapFromAngle := 0.0
var wrapToAngle := 0.0
var wrapFromDistance := 0.0
var wrapToDistance := 0.0
var wrapArcLength := 0.0
var wrapExitOffset := Vector2.ZERO # Straight move after the arc, onto the new surface.
var wrapFromRotation := 0.0
var wrapToRotation := 0.0
var wrapOntoNormal := Vector2.UP # Normal of the surface we end up on.
var wrapSpeed := 0.0 # Eases up to GROUND_SPEED, so starting from a standstill isn't a jolt.
var wrapTravelled := 0.0
# ---- Lip ----
# Fallback for going over a ceiling edge without the edge hold catching it:
# we hang just past the edge for HOLD_TIME, and pressing up wraps onto the wall above.
const CLIMB_INPUT_BUFFER = 0.15 # Tapping up this long before reaching a lip still counts.
var isHangingOnLip := false
var timeSpentOnLip := 0.0
var lipDirection := 0.0 # Which way we were moving when we went over the lip.
var timeSinceUpPressed := 1.0
# ---- Hops ----
# Holding up (and not left/right) on the floor for HOLD_TIME hops just high
# enough to reach a ceiling up to HOP_REACH above us (measured from our top).
# With no ceiling in reach it's just a little HOP_NO_CEILING_HEIGHT hop.
# Walls and ceilings work the same way with the direction away from them (also
# only while not moving along them), but with nothing in reach we let go as
# usual instead of doing a little hop.
const HOP_REACH = 32.0
const HOP_NO_CEILING_HEIGHT = 16.0
const HOP_OVERSHOOT = 2.0 # Aim slightly past the surface so we still hit it with some speed.
var timeSpentHoldingUpOnFloor := 0.0
var isHoppingAcross := false # Hopping from a wall to the one opposite: no air steering until we land.
# ---- Visuals and sound ----
const ROTATE_TO_SURFACE_SPEED = 25.0 # How quickly the sprite turns to sit on a wall or ceiling.
const MIN_LAND_SPEED = 60.0 # Slower impacts than this don't splat.
const LAND_PITCH_MIN = 0.87
const LAND_PITCH_MAX = 1.15
# Placeholder sounds, see Assets/Sounds/CREDITS.txt. One is picked at random
# for each landing, at a slightly random pitch, so they don't all sound the same.
@export var landSounds: Array[AudioStream] = []
# Temp for now, need to use AnimatedSprite2D later on.
@onready var sprite: Sprite2D = $Sprite2D
@onready var collisionShape: CollisionShape2D = $CollisionShape2D
@onready var edgeSensors: Node2D = $EdgeSensors
@onready var leftEdgeSensor: RayCast2D = $EdgeSensors/LeftEdgeSensor
@ -32,77 +108,10 @@ const WALL_STICK_SPEED = 20.0 # Small push into the wall that keeps the slime pr
@onready var splatParticles: CPUParticles2D = $SplatParticles
@onready var landSound: AudioStreamPlayer = $LandSound
@onready var wrapSound: AudioStreamPlayer = $WrapSound
# Placeholder sounds, see Assets/Sounds/CREDITS.txt. One is picked at random
# for each landing, at a slightly random pitch, so they don't all sound the same.
@export var landSounds: Array[AudioStream] = []
const MIN_LAND_SPEED = 60.0 # Slower impacts than this don't splat.
# How long to press opposite direction before unsticking from a wall/ceiling
const MAX_SECS_TO_UNSTICK = 0.5
# Hop: holding up (and not left/right) on the floor for MAX_SECS_TO_UNSTICK hops just high enough
# to reach a ceiling up to HOP_MAX_HEIGHT above us (measured from our top).
# With no ceiling in reach it's just a little HOP_NO_CEILING_HEIGHT hop.
# Walls and ceilings work the same way with the direction away from them (also
# only while not moving along them), but with nothing in reach we let go as
# usual instead of doing a little hop.
const HOP_MAX_HEIGHT = 32.0
const HOP_NO_CEILING_HEIGHT = 16.0
const HOP_OVERSHOOT = 2.0 # Aim slightly past the ceiling so we still hit it with some speed.
var timeSpentHoldingUpOnFloor := 0.0
var isHoppingAcross := false # Hopping from a wall to the one opposite: no air steering until we land.
var isStickingToWall := false
var timeSpentUnstickingWall = 0.0
var wallNormalX := 0.0
var isStickingToCeiling := false
var timeSpentUnstickingCeiling = 0.0
var isClimbingLip = false
var timeSpentUnstickingLip= 0.0
var lipDirection := 0.0 # Which way we were moving when we went over the lip.
# After climbing onto a wall from a lip we're usually still holding away from it,
# so don't count that towards unsticking until the direction is released.
var ignoreWallUnstickUntilRelease := false
# Same for down after wrapping onto a ceiling (e.g. crawling down a wall and under).
var ignoreCeilingUnstickUntilRelease := false
# Edge wrapping: instead of relying on physics to slide around a corner, the
# slime swings around it on a quarter circle so it always feels the same.
const WRAP_MARGIN = 0.5 # Extra gap from the corner so we don't clip into it.
const CLIMB_INPUT_BUFFER = 0.15 # Tapping up this long before reaching a lip still counts.
var isWrapping := false
var wrapCorner := Vector2.ZERO
var wrapFromAngle := 0.0
var wrapToAngle := 0.0
var wrapFromDistance := 0.0
var wrapToDistance := 0.0
var wrapFromRotation := 0.0
var wrapToRotation := 0.0
var wrapSpeed := 0.0 # Eases up to GROUND_SPEED, so starting from a standstill isn't a jolt.
var wrapTravelled := 0.0
var wrapArcLength := 0.0
var wrapExitOffset := Vector2.ZERO # Straight move after the arc, onto the new surface.
var wrapOntoNormal := Vector2.UP # Normal of the surface we end up on.
var timeSinceUpPressed := 1.0
var wrapEntryStart := Vector2.ZERO # Where a straight move before the arc starts from.
var wrapEntryLength := 0.0
# Surface edges: the edge sensors are rotated to point into whatever surface
# we're on, a little way to each side of us. If one stops touching the surface,
# there's an edge within edgeSensorRange on that side, and pressing into the
# surface will slide over it onto the side of the platform.
@export var edgeSensorRange := 12.0
var wallFacingY := -1.0 # Which way we last moved along a wall (-1 is up).
# Holding at an edge: moving along a surface towards its edge stops at the edge,
# and only lets go after holding towards it for MAX_SECS_TO_UNSTICK.
var timeSpentHoldingEdge := 0.0
func _ready() -> void:
floor_snap_length = SURFACE_SNAP_DISTANCE
var sensorDepth := _get_radius() + 4
var sensorDepth := _get_radius() + EDGE_SENSOR_DEPTH
leftEdgeSensor.position = Vector2(-edgeSensorRange, 0)
leftEdgeSensor.target_position = Vector2(0, sensorDepth)
rightEdgeSensor.position = Vector2(edgeSensorRange, 0)
@ -112,18 +121,7 @@ func _ready() -> void:
leftEdgeSensor.add_exception(self)
rightEdgeSensor.add_exception(self)
# Rotates the sprite to sit on the wall or ceiling. Done in _physics_process
# (not _process) so physics interpolation smooths it along with our movement.
func _update_sprite_rotation(delta: float) -> void:
# In a corner only one of these is ever true (decided in _physics_process).
var target := 0.0
if not is_on_floor() and isStickingToWall: target = PI/2 * wallNormalX
elif isStickingToCeiling: target = PI
# Exponential smoothing, so it turns at the same rate at any frame rate.
sprite.rotation = lerp_angle(sprite.rotation, target, 1.0 - exp(-ROTATE_TO_WALL_SPEED * delta))
func _physics_process(delta: float) -> void:
# Get the input direction and handle the movement/deceleration.
var horizontalInput := Input.get_axis("moveLeft", "moveRight")
var verticalInput := Input.get_axis("moveDown", "moveUp")
@ -135,87 +133,24 @@ func _physics_process(delta: float) -> void:
_update_wrap(delta)
return
var wasInAir := _get_surface_normal() == Vector2.ZERO and not isClimbingLip
var wasInAir := _get_surface_normal() == Vector2.ZERO and not isHangingOnLip
if not wasInAir: isHoppingAcross = false
# Hanging on a lip and pressing up: swing around onto the wall above.
var wantsToClimb := verticalInput > 0 or timeSinceUpPressed <= CLIMB_INPUT_BUFFER
if isClimbingLip and wantsToClimb and _start_lip_wrap():
if isHangingOnLip and wantsToClimb and _start_lip_wrap():
return
# Near the edge of a surface and pressing into it: slide over onto the
# Near the edge of a surface and pressing into it: wrap over onto the
# side of the platform.
if isStickingToWall and verticalInput: wallFacingY = -signf(verticalInput)
if _start_edge_wrap(horizontalInput, verticalInput):
return
# Quick flip sprite thing.
if horizontalInput:
if isStickingToCeiling: sprite.flip_h = (horizontalInput > 0)
else: sprite.flip_h = (horizontalInput < 0)
# Vertical Input Controls
if isStickingToCeiling:
# If on ceiling, pressing down long enough (while not moving along it)
# unsticks from ceiling.
if verticalInput >= 0: ignoreCeilingUnstickUntilRelease = false
if verticalInput < 0 and not horizontalInput and not ignoreCeilingUnstickUntilRelease:
timeSpentUnstickingCeiling += delta
else: timeSpentUnstickingCeiling = 0.0
if timeSpentUnstickingCeiling >= MAX_SECS_TO_UNSTICK:
isStickingToCeiling = false
# With a floor within reach below: hop down onto it. Otherwise just let go.
var floorDistance := _get_hop_distance(Vector2.DOWN)
if floorDistance >= 0.0: velocity.y = sqrt(2.0 * get_gravity().y * floorDistance)
else: velocity.y = get_gravity().y * delta
else: velocity.y = CEILING_STICK_SPEED
# Move up and down along a wall when sticking to it.
elif isStickingToWall:
velocity.y = _accelerate(velocity.y, CLIMB_SPEED * verticalInput)
# Don't fall if climbing lip. Pressing up climbs onto the wall above.
elif isClimbingLip:
velocity.y = CLIMB_SPEED if verticalInput > 0 else 0.0
# Else... just fall.
elif not is_on_floor():
velocity.y = minf(velocity.y + get_gravity().y * delta, MAX_FALL_SPEED)
# On the floor and standing still, holding up long enough hops up to the
# ceiling above. Not against a wall though, where up climbs it instead.
if is_on_floor() and not isStickingToWall and verticalInput > 0 and not horizontalInput:
timeSpentHoldingUpOnFloor += delta
else: timeSpentHoldingUpOnFloor = 0.0
if timeSpentHoldingUpOnFloor >= MAX_SECS_TO_UNSTICK:
timeSpentHoldingUpOnFloor = 0.0
velocity.y = -sqrt(2.0 * get_gravity().y * _get_hop_height())
# Horizontal Input Controls
# If sticking to a wall, pressing away from it long enough (while not
# climbing) gets us unstuck.
if isStickingToWall and not is_on_floor():
var pressingAwayFromWall := horizontalInput * wallNormalX > 0
if not pressingAwayFromWall: ignoreWallUnstickUntilRelease = false
if pressingAwayFromWall and not verticalInput and not ignoreWallUnstickUntilRelease:
timeSpentUnstickingWall += delta
else: timeSpentUnstickingWall = 0.0
if timeSpentUnstickingWall >= MAX_SECS_TO_UNSTICK:
# With a wall within reach opposite: hop across to it. Otherwise just let go.
var wallDistance := _get_hop_distance(Vector2(wallNormalX, 0))
if wallDistance >= 0.0: _hop_across(wallDistance)
else: velocity.x = horizontalInput * GROUND_SPEED
else:
velocity.x = -wallNormalX * WALL_STICK_SPEED
# Otherwise move horizontally based on what we're on.
else:
timeSpentUnstickingWall = 0.0
# Hang on the lip. Pressing up pushes back towards the platform so we
# slide around the corner and touch the wall.
if isClimbingLip:
velocity.x = -lipDirection * WALL_STICK_SPEED if verticalInput > 0 else 0.0
elif is_on_floor() or isStickingToCeiling:
velocity.x = _accelerate(velocity.x, horizontalInput * GROUND_SPEED)
elif not isHoppingAcross:
velocity.x = _air_steer(velocity.x, horizontalInput)
_update_facing(horizontalInput)
_update_vertical_movement(delta, horizontalInput, verticalInput)
_update_floor_hop(delta, horizontalInput, verticalInput)
_update_horizontal_movement(delta, horizontalInput, verticalInput)
_hold_at_edge(delta)
var wasOnWall := isStickingToWall and not is_on_floor()
@ -223,46 +158,18 @@ func _physics_process(delta: float) -> void:
move_and_slide()
# Check if we should be sticking to walls/ceiling after moving our player.
# If we drifted slightly off the wall (and aren't trying to let go), pull
# back onto it instead of falling off.
isStickingToWall = is_on_wall() or (wasOnWall and timeSpentUnstickingWall < MAX_SECS_TO_UNSTICK \
and _snap_to_surface(Vector2(wallNormalX, 0)))
_update_wall_sticking(wasOnWall)
# Climbed past the top of a wall: swing over onto the floor on top.
if wasOnWall and not isStickingToWall and verticalInput > 0 \
and timeSpentUnstickingWall < MAX_SECS_TO_UNSTICK and _start_wall_top_wrap():
and timeSpentUnstickingWall < HOLD_TIME and _start_wall_top_wrap():
return
if isStickingToWall:
wallNormalX = get_wall_normal().x
# Set if we're sticking to a ceiling.
# Also check if we started climbing a lip.
if isClimbingLip:
timeSpentUnstickingLip += delta
if timeSpentUnstickingLip >= MAX_SECS_TO_UNSTICK:
isClimbingLip = false
else: timeSpentUnstickingLip = 0.0
var wasJustOnCeiling = isStickingToCeiling
isStickingToCeiling = is_on_ceiling() or (wasJustOnCeiling and _snap_to_surface(Vector2.DOWN))
# Only walking off the ceiling's edge counts as a lip, not landing on
# a ceiling, letting go of it by pressing down, or after already holding
# at the edge long enough to let go.
if wasJustOnCeiling and not isStickingToCeiling and not isStickingToWall and velocity.x \
and timeSpentHoldingEdge < MAX_SECS_TO_UNSTICK:
isClimbingLip = true
lipDirection = signf(velocity.x)
# Made it onto the wall from the lip.
if isClimbingLip and isStickingToWall:
isClimbingLip = false
ignoreWallUnstickUntilRelease = true
_update_ceiling_sticking(delta)
# In a corner touching both wall and ceiling, only stick to one
# surface depending on if we're pressing into the ceiling or not.
if isStickingToWall and isStickingToCeiling:
if verticalInput > 0:
isStickingToWall = false
else:
isStickingToCeiling = false
if verticalInput > 0: isStickingToWall = false
else: isStickingToCeiling = false
# Just landed on something: squish.
var normal := _get_surface_normal()
@ -271,37 +178,127 @@ func _physics_process(delta: float) -> void:
_update_sprite_rotation(delta)
# How high to hop: up to the ceiling above us if there's one in reach.
func _get_hop_height() -> float:
var distance := _get_hop_distance(Vector2.UP)
return distance if distance >= 0.0 else HOP_NO_CEILING_HEIGHT
# ---- Movement steps (in the order _physics_process runs them) ----
# How far to hop in direction to reach a surface facing us within
# HOP_MAX_HEIGHT (plus HOP_OVERSHOOT), or -1 if there isn't one.
func _get_hop_distance(direction: Vector2) -> float:
var hit := move_and_collide(direction * HOP_MAX_HEIGHT, true)
if hit and hit.get_normal().dot(-direction) > 0.5:
return hit.get_travel().length() + HOP_OVERSHOOT
return -1.0
# Flips the sprite to face the way we're moving. Upside down on a ceiling, so flipped the other way.
func _update_facing(horizontalInput: float) -> void:
if not horizontalInput: return
if isStickingToCeiling: sprite.flip_h = horizontalInput > 0
else: sprite.flip_h = horizontalInput < 0
# Hops from the wall we're on to the one distance away opposite, at crawling
# speed, on an arc that lands at the same height we left from.
func _hop_across(distance: float) -> void:
var flightTime := distance / GROUND_SPEED
velocity.x = wallNormalX * GROUND_SPEED
velocity.y = -0.5 * get_gravity().y * flightTime
isHoppingAcross = true
func _update_vertical_movement(delta: float, horizontalInput: float, verticalInput: float) -> void:
if isStickingToCeiling:
# Pressing down long enough (while not moving along the ceiling) lets go of it.
if verticalInput >= 0: ignoreCeilingUnstickUntilRelease = false
if verticalInput < 0 and not horizontalInput and not ignoreCeilingUnstickUntilRelease:
timeSpentUnstickingCeiling += delta
else: timeSpentUnstickingCeiling = 0.0
if timeSpentUnstickingCeiling >= HOLD_TIME:
isStickingToCeiling = false
# With a floor within reach below: hop down onto it. Otherwise just let go.
var floorDistance := _get_hop_distance(Vector2.DOWN)
if floorDistance >= 0.0: velocity.y = sqrt(2.0 * get_gravity().y * floorDistance)
else: velocity.y = get_gravity().y * delta
else: velocity.y = -CEILING_STICK_SPEED
# Move up and down along a wall when sticking to it.
elif isStickingToWall:
velocity.y = _accelerate(velocity.y, -CLIMB_SPEED * verticalInput, delta)
# Don't fall while hanging on a lip. Pressing up there normally starts a lip
# wrap first; this only climbs if the wrap couldn't find the corner.
elif isHangingOnLip:
velocity.y = -CLIMB_SPEED if verticalInput > 0 else 0.0
elif not is_on_floor():
velocity.y = minf(velocity.y + get_gravity().y * delta, MAX_FALL_SPEED)
# On the floor and standing still, holding up long enough hops up to the
# ceiling above. Not against a wall though, where up climbs it instead.
func _update_floor_hop(delta: float, horizontalInput: float, verticalInput: float) -> void:
if is_on_floor() and not isStickingToWall and verticalInput > 0 and not horizontalInput:
timeSpentHoldingUpOnFloor += delta
else: timeSpentHoldingUpOnFloor = 0.0
if timeSpentHoldingUpOnFloor >= HOLD_TIME:
timeSpentHoldingUpOnFloor = 0.0
velocity.y = -sqrt(2.0 * get_gravity().y * _get_hop_height())
func _update_horizontal_movement(delta: float, horizontalInput: float, verticalInput: float) -> void:
# On a wall, pressing away from it long enough (while not climbing) hops
# across to the opposite wall or lets go.
if isStickingToWall and not is_on_floor():
var pressingAwayFromWall := horizontalInput * wallNormalX > 0
if not pressingAwayFromWall: ignoreWallUnstickUntilRelease = false
if pressingAwayFromWall and not verticalInput and not ignoreWallUnstickUntilRelease:
timeSpentUnstickingWall += delta
else: timeSpentUnstickingWall = 0.0
if timeSpentUnstickingWall >= HOLD_TIME:
# With a wall within reach opposite: hop across to it. Otherwise just let go.
var wallDistance := _get_hop_distance(Vector2(wallNormalX, 0))
if wallDistance >= 0.0: _hop_across(wallDistance)
else: velocity.x = horizontalInput * GROUND_SPEED
else:
velocity.x = -wallNormalX * WALL_STICK_SPEED
return
timeSpentUnstickingWall = 0.0
# Hanging on a lip. Pressing up there normally starts a lip wrap first; if
# that couldn't find the corner, push back towards the platform so physics
# slides us around it onto the wall instead.
if isHangingOnLip:
velocity.x = -lipDirection * WALL_STICK_SPEED if verticalInput > 0 else 0.0
elif is_on_floor() or isStickingToCeiling:
velocity.x = _accelerate(velocity.x, horizontalInput * GROUND_SPEED, delta)
elif not isHoppingAcross:
velocity.x = _air_steer(velocity.x, horizontalInput, delta)
# After moving: are we still on the wall? If we drifted slightly off it (and
# aren't trying to let go), pull back onto it instead of falling off.
func _update_wall_sticking(wasOnWall: bool) -> void:
isStickingToWall = is_on_wall() or (wasOnWall and timeSpentUnstickingWall < HOLD_TIME \
and _snap_to_surface(Vector2(wallNormalX, 0)))
if isStickingToWall: wallNormalX = get_wall_normal().x
# After moving: are we still on the ceiling, and did we just go over its edge
# onto a lip?
func _update_ceiling_sticking(delta: float) -> void:
if isHangingOnLip:
timeSpentOnLip += delta
if timeSpentOnLip >= HOLD_TIME: isHangingOnLip = false
else: timeSpentOnLip = 0.0
var wasOnCeiling := isStickingToCeiling
isStickingToCeiling = is_on_ceiling() or (wasOnCeiling and _snap_to_surface(Vector2.DOWN))
# Only walking off the ceiling's edge counts as a lip, not landing on
# a ceiling, letting go of it by pressing down, or after already holding
# at the edge long enough to let go.
if wasOnCeiling and not isStickingToCeiling and not isStickingToWall and velocity.x != 0.0 \
and timeSpentHoldingEdge < HOLD_TIME:
isHangingOnLip = true
lipDirection = signf(velocity.x)
# Made it onto the wall from the lip.
if isHangingOnLip and isStickingToWall:
isHangingOnLip = false
ignoreWallUnstickUntilRelease = true
# Rotates the sprite to sit on the wall or ceiling. Done in _physics_process
# (not _process) so physics interpolation smooths it along with our movement.
func _update_sprite_rotation(delta: float) -> void:
# In a corner only one of these is ever true (decided in _physics_process).
var target := 0.0
if not is_on_floor() and isStickingToWall: target = PI/2 * wallNormalX
elif isStickingToCeiling: target = PI
# Exponential smoothing, so it turns at the same rate at any frame rate.
sprite.rotation = lerp_angle(sprite.rotation, target, 1.0 - exp(-ROTATE_TO_SURFACE_SPEED * delta))
# ---- Movement helpers ----
# Moves speed towards target: GROUND_ACCEL when speeding up, GROUND_FRICTION
# when slowing down or stopping.
func _accelerate(speed: float, target: float) -> float:
func _accelerate(speed: float, target: float, delta: float) -> float:
var speedingUp := target != 0.0 and (speed == 0.0 or signf(target) == signf(speed)) and absf(target) > absf(speed)
return move_toward(speed, target, (GROUND_ACCEL if speedingUp else GROUND_FRICTION) * get_physics_process_delta_time())
return move_toward(speed, target, (GROUND_ACCEL if speedingUp else GROUND_FRICTION) * delta)
# Horizontal steering in the air. Extra speed from leaving a surface fades
# slowly unless we steer against it.
func _air_steer(speed: float, horizontalInput: float) -> float:
var delta := get_physics_process_delta_time()
func _air_steer(speed: float, horizontalInput: float, delta: float) -> float:
var target := horizontalInput * AIR_SPEED
var keepingMomentum := absf(speed) > AIR_SPEED and (horizontalInput == 0.0 or signf(horizontalInput) == signf(speed))
if keepingMomentum or horizontalInput == 0.0:
@ -312,78 +309,11 @@ func _air_steer(speed: float, horizontalInput: float) -> float:
# against it and return true. Only counts if we'd hit it head on, so sliding
# off an edge and catching its corner doesn't pull us back around.
func _snap_to_surface(normal: Vector2) -> bool:
var motion := -normal * SURFACE_SNAP_DISTANCE
var hit := move_and_collide(motion, true)
var hit := move_and_collide(-normal * SURFACE_SNAP_DISTANCE, true)
if not hit or hit.get_normal().dot(normal) < 0.9: return false
global_position += hit.get_travel()
return true
# Squish sound and a little burst of slime where we hit the surface.
func _splat(normal: Vector2) -> void:
splatParticles.global_position = global_position - normal * _get_radius()
# It's a jump to a new spot, not movement, so don't interpolate from the last one.
splatParticles.reset_physics_interpolation()
splatParticles.direction = normal
splatParticles.restart()
if landSounds:
landSound.stream = landSounds.pick_random()
landSound.pitch_scale = randf_range(0.87, 1.15)
landSound.play()
func _get_radius() -> float:
return (collisionShape.shape as CircleShape2D).radius
func _cast_ray(from: Vector2, to: Vector2) -> Dictionary:
var query := PhysicsRayQueryParameters2D.create(from, to, collision_mask, [get_rid()])
return get_world_2d().direct_space_state.intersect_ray(query)
func _is_point_free(point: Vector2) -> bool:
var query := PhysicsPointQueryParameters2D.new()
query.position = point
query.collision_mask = collision_mask
query.exclude = [get_rid()]
return get_world_2d().direct_space_state.intersect_point(query, 1).is_empty()
func _is_spot_free(spot: Vector2) -> bool:
var query := PhysicsShapeQueryParameters2D.new()
query.shape = collisionShape.shape
query.transform = Transform2D(0.0, spot)
query.collision_mask = collision_mask
query.exclude = [get_rid()]
return get_world_2d().direct_space_state.intersect_shape(query, 1).is_empty()
# Just went over a ceiling edge: find the corner and swing up beside the wall.
func _start_lip_wrap() -> bool:
var dir := lipDirection
var radius := _get_radius()
var pos := global_position
# Bottom of the platform we just came off of.
var ceilingHit := _cast_ray(pos - Vector2(dir * (radius + 2), 0), pos - Vector2(dir * (radius + 2), radius * 2))
if not ceilingHit or ceilingHit.normal.y < 0.5: return false
var ceilingY: float = ceilingHit.position.y
# Side of the platform, just above its bottom.
var faceHit := _cast_ray(Vector2(pos.x + dir * radius, ceilingY - 2), Vector2(pos.x - dir * radius * 2, ceilingY - 2))
if not faceHit or faceHit.normal.x * dir < 0.5: return false
var corner := Vector2(faceHit.position.x, ceilingY)
# After the arc, carry on up the wall so our side is flat against it.
return _begin_wrap(corner, Vector2(dir, 0).angle(), Vector2(0, -radius), Vector2(dir, 0))
# Just climbed past the top of a wall: find the corner and swing up on top.
func _start_wall_top_wrap() -> bool:
var n := wallNormalX
var radius := _get_radius()
var pos := global_position
# Top of the platform, just past the wall.
var topHit := _cast_ray(pos + Vector2(-n * (radius + 2), -radius), pos + Vector2(-n * (radius + 2), radius * 2))
if not topHit or topHit.normal.y > -0.5: return false
var topY: float = topHit.position.y
# Side of the platform, just below its top.
var faceHit := _cast_ray(Vector2(pos.x + n * 2, topY + 2), Vector2(pos.x - n * radius * 2, topY + 2))
if not faceHit or faceHit.normal.x * n < 0.5: return false
var corner := Vector2(faceHit.position.x, topY)
# After the arc, carry on onto the platform instead of perching on its corner.
return _begin_wrap(corner, -PI/2, Vector2(-n * radius, 0), Vector2.UP)
# Normal of the surface we're stuck to, or zero if we're in the air.
func _get_surface_normal() -> Vector2:
if is_on_floor(): return Vector2.UP
@ -397,10 +327,35 @@ func _get_facing() -> Vector2:
if isStickingToCeiling: return Vector2(1 if sprite.flip_h else -1, 0)
return Vector2(0, wallFacingY)
# ---- Hops ----
# How high to hop from the floor: up to the ceiling above us if there's one in reach.
func _get_hop_height() -> float:
var distance := _get_hop_distance(Vector2.UP)
return distance if distance >= 0.0 else HOP_NO_CEILING_HEIGHT
# How far to hop in direction to reach a surface facing us within HOP_REACH
# (plus HOP_OVERSHOOT), or -1 if there isn't one.
func _get_hop_distance(direction: Vector2) -> float:
var hit := move_and_collide(direction * HOP_REACH, true)
if hit and hit.get_normal().dot(-direction) > 0.5:
return hit.get_travel().length() + HOP_OVERSHOOT
return -1.0
# Hops from the wall we're on to the one distance away opposite, at crawling
# speed, on an arc that lands at the same height we left from.
func _hop_across(distance: float) -> void:
var flightTime := distance / GROUND_SPEED
velocity.x = wallNormalX * GROUND_SPEED
velocity.y = -0.5 * get_gravity().y * flightTime
isHoppingAcross = true
# ---- Surface edges ----
# Pressing into the surface we're on: if there's an edge in range, slide to it
# and over onto the side of the platform. Holding a direction along the surface
# picks that side, otherwise we go the way we're facing, or the other way if
# only that side has an edge.
# and wrap over onto the side of the platform. Holding a direction along the
# surface picks that side, otherwise we go the way we're facing, or the other
# way if only that side has an edge.
func _start_edge_wrap(horizontalInput: float, verticalInput: float) -> bool:
var normal := _get_surface_normal()
if normal == Vector2.ZERO: return false
@ -415,42 +370,43 @@ func _start_edge_wrap(horizontalInput: float, verticalInput: float) -> bool:
var facing := 1.0 if _get_facing().dot(tangent) >= 0 else -1.0
return _try_edge_wrap(normal, tangent, facing) or _try_edge_wrap(normal, tangent, -facing)
# Tries wrapping over the edge on one side (side is -1 or 1 along tangent).
func _try_edge_wrap(normal: Vector2, tangent: Vector2, side: float) -> bool:
var sensor := rightEdgeSensor if side > 0 else leftEdgeSensor
sensor.force_raycast_update()
if sensor.is_colliding(): return false
# A sensor starting inside something is an inside corner, not an edge.
if not _is_point_free(sensor.global_position): return false
var dir := tangent * side
var corner = _find_edge_corner(normal, dir, edgeSensorRange + 2)
var direction := tangent * side
var corner = _find_edge_corner(normal, direction, edgeSensorRange + 2)
if corner == null: return false
# Slide to just past the corner, swing around it, then carry on along the
# side of the platform so we end up flat against it.
return _begin_wrap(corner, dir.angle(), -normal * _get_radius(), dir, normal.angle())
return _begin_wrap(corner, direction.angle(), -normal * _get_radius(), direction, normal.angle())
# Finds the corner where the surface we're on (facing normal) ends, up to reach
# ahead of us in dir. Returns null if there's no edge that close.
func _find_edge_corner(normal: Vector2, dir: Vector2, reach: float) -> Variant:
# ahead of us in direction. Returns null if there's no edge that close.
func _find_edge_corner(normal: Vector2, direction: Vector2, reach: float) -> Variant:
var radius := _get_radius()
var pos := global_position
# The surface we're on, checked from the side away from the edge.
var surfaceFrom := pos - dir * radius * 0.5
var surfaceFrom := pos - direction * radius * 0.5
var surfaceHit := _cast_ray(surfaceFrom, surfaceFrom - normal * radius * 2)
if not surfaceHit or surfaceHit.normal.dot(normal) < 0.5: return null
# Side of the platform, just inside its surface, looking back from reach
# ahead. If the surface carries on past reach, the ray starts inside it
# and finds nothing.
var line: Vector2 = surfaceHit.position - normal * 2 + dir * (pos - surfaceHit.position).dot(dir)
var faceHit := _cast_ray(line + dir * reach, line - dir * radius)
if not faceHit or faceHit.normal.dot(dir) < 0.5: return null
var line: Vector2 = surfaceHit.position - normal * 2 + direction * (pos - surfaceHit.position).dot(direction)
var faceHit := _cast_ray(line + direction * reach, line - direction * radius)
if not faceHit or faceHit.normal.dot(direction) < 0.5: return null
var corner: Vector2 = faceHit.position + normal * 2
# A real edge has empty space just past it, behind the surface. Seams
# between tiles (and the foot of a wall) have solid there, so they're not edges.
if not _is_point_free(corner + dir * 2 - normal * 2): return null
if not _is_point_free(corner + direction * 2 - normal * 2): return null
return corner
# If this frame's movement along the surface would take us past its edge, stop
# at the edge instead, until we've held towards it for MAX_SECS_TO_UNSTICK.
# at the edge instead, until we've held towards it for HOLD_TIME.
func _hold_at_edge(delta: float) -> void:
var normal := _get_surface_normal()
var tangent := normal.orthogonal()
@ -458,19 +414,53 @@ func _hold_at_edge(delta: float) -> void:
if normal == Vector2.ZERO or is_zero_approx(speed):
timeSpentHoldingEdge = 0.0
return
var dir := tangent * signf(speed)
var direction := tangent * signf(speed)
# Climbing up past the top of a wall swings over onto it instead.
if absf(normal.x) > 0.5 and dir.y < 0: return
if absf(normal.x) > 0.5 and direction.y < 0: return
var step := absf(speed) * delta
var corner = _find_edge_corner(normal, dir, step + 1)
var distanceToEdge: float = INF if corner == null else (corner - global_position).dot(dir)
var corner = _find_edge_corner(normal, direction, step + 1)
var distanceToEdge: float = INF if corner == null else (corner - global_position).dot(direction)
if distanceToEdge > step:
timeSpentHoldingEdge = 0.0
return
# Held long enough: let go and carry on over the edge.
if timeSpentHoldingEdge >= MAX_SECS_TO_UNSTICK: return
if timeSpentHoldingEdge >= HOLD_TIME: return
timeSpentHoldingEdge += delta
velocity += dir * (maxf(distanceToEdge, 0.0) / delta - absf(speed))
velocity += direction * (maxf(distanceToEdge, 0.0) / delta - absf(speed))
# Just went over a ceiling edge: find the corner and swing up beside the wall.
func _start_lip_wrap() -> bool:
var direction := lipDirection
var radius := _get_radius()
var pos := global_position
# Bottom of the platform we just came off of.
var ceilingHit := _cast_ray(pos - Vector2(direction * (radius + 2), 0), pos - Vector2(direction * (radius + 2), radius * 2))
if not ceilingHit or ceilingHit.normal.y < 0.5: return false
var ceilingY: float = ceilingHit.position.y
# Side of the platform, just above its bottom.
var faceHit := _cast_ray(Vector2(pos.x + direction * radius, ceilingY - 2), Vector2(pos.x - direction * radius * 2, ceilingY - 2))
if not faceHit or faceHit.normal.x * direction < 0.5: return false
var corner := Vector2(faceHit.position.x, ceilingY)
# After the arc, carry on up the wall so our side is flat against it.
return _begin_wrap(corner, Vector2(direction, 0).angle(), Vector2(0, -radius), Vector2(direction, 0))
# Just climbed past the top of a wall: find the corner and swing up on top.
func _start_wall_top_wrap() -> bool:
var wallNormal := wallNormalX
var radius := _get_radius()
var pos := global_position
# Top of the platform, just past the wall.
var topHit := _cast_ray(pos + Vector2(-wallNormal * (radius + 2), -radius), pos + Vector2(-wallNormal * (radius + 2), radius * 2))
if not topHit or topHit.normal.y > -0.5: return false
var topY: float = topHit.position.y
# Side of the platform, just below its top.
var faceHit := _cast_ray(Vector2(pos.x + wallNormal * 2, topY + 2), Vector2(pos.x - wallNormal * radius * 2, topY + 2))
if not faceHit or faceHit.normal.x * wallNormal < 0.5: return false
var corner := Vector2(faceHit.position.x, topY)
# After the arc, carry on onto the platform instead of perching on its corner.
return _begin_wrap(corner, -PI/2, Vector2(-wallNormal * radius, 0), Vector2.UP)
# ---- Edge wrapping ----
# Starts swinging around corner to toAngle from it, then moving by exitOffset,
# ending up stuck to the surface facing ontoNormal.
@ -493,12 +483,11 @@ func _begin_wrap(corner: Vector2, toAngle: float, exitOffset: Vector2, ontoNorma
wrapEntryLength = global_position.distance_to(corner + Vector2.from_angle(fromAngle) * radius)
wrapToAngle = toAngle
wrapToDistance = radius
wrapArcLength = absf(angle_difference(wrapFromAngle, wrapToAngle)) * radius
wrapExitOffset = exitOffset
wrapFromRotation = sprite.rotation
wrapToRotation = ontoNormal.angle() + PI/2
wrapExitOffset = exitOffset
wrapOntoNormal = ontoNormal
# Keep the same speed as crawling along a surface.
wrapArcLength = absf(angle_difference(wrapFromAngle, wrapToAngle)) * radius
wrapTravelled = 0.0
# Start at the speed we were already going, so crawling into a wrap is seamless.
wrapSpeed = minf(velocity.length(), GROUND_SPEED)
@ -528,7 +517,9 @@ func _update_wrap(delta: float) -> void:
global_position = wrapCorner + Vector2.from_angle(angle) * distance + wrapExitOffset * exitProgress
sprite.rotation = lerp_angle(wrapFromRotation, wrapToRotation, arcProgress)
if wrapTravelled < totalLength: return
_finish_wrap(delta)
func _finish_wrap(delta: float) -> void:
# Close the small gap left by WRAP_MARGIN so we're touching the new surface.
# Done with move_and_slide so is_on_floor()/is_on_wall() are up to date
# instead of still describing where we were before the wrap.
@ -552,10 +543,48 @@ func _update_wrap(delta: float) -> void:
velocity = exitDirection * wrapSpeed
isWrapping = false
isClimbingLip = false
isHangingOnLip = false
isStickingToCeiling = wrapOntoNormal.y > 0.5
isStickingToWall = absf(wrapOntoNormal.x) > 0.5
if isStickingToWall:
wallNormalX = wrapOntoNormal.x
ignoreWallUnstickUntilRelease = true
ignoreCeilingUnstickUntilRelease = isStickingToCeiling
# ---- Effects ----
# Squish sound and a little burst of slime where we hit the surface.
func _splat(normal: Vector2) -> void:
splatParticles.global_position = global_position - normal * _get_radius()
# It's a jump to a new spot, not movement, so don't interpolate from the last one.
splatParticles.reset_physics_interpolation()
splatParticles.direction = normal
splatParticles.restart()
if landSounds:
landSound.stream = landSounds.pick_random()
landSound.pitch_scale = randf_range(LAND_PITCH_MIN, LAND_PITCH_MAX)
landSound.play()
# ---- Physics queries ----
func _get_radius() -> float:
return (collisionShape.shape as CircleShape2D).radius
func _cast_ray(from: Vector2, to: Vector2) -> Dictionary:
var query := PhysicsRayQueryParameters2D.create(from, to, collision_mask, [get_rid()])
return get_world_2d().direct_space_state.intersect_ray(query)
func _is_point_free(point: Vector2) -> bool:
var query := PhysicsPointQueryParameters2D.new()
query.position = point
query.collision_mask = collision_mask
query.exclude = [get_rid()]
return get_world_2d().direct_space_state.intersect_point(query, 1).is_empty()
func _is_spot_free(spot: Vector2) -> bool:
var query := PhysicsShapeQueryParameters2D.new()
query.shape = collisionShape.shape
query.transform = Transform2D(0.0, spot)
query.collision_mask = collision_mask
query.exclude = [get_rid()]
return get_world_2d().direct_space_state.intersect_shape(query, 1).is_empty()