SlimePlatformer/Characters/player.gd
SnekInAScarf cb0ce427aa Trim player.gd comments: shorter, and none that restate the code
Only comments and blank lines changed (the code with comments stripped
is identical). Shortened the overview, section headers and longer
explanations, and removed comments that just describe the next line.
Kept the ones explaining why or non-obvious maths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 18:32:13 -07:00

685 lines
25 KiB
GDScript
Executable file

extends CharacterBody2D
# The slime crawls on floors, walls and ceilings and sticks to them.
# - Let go: hold away from a wall or ceiling for HOLD_TIME.
# - Edge hold: crawling to an edge stops there until you've held towards it for HOLD_TIME.
# - Edge wrap: near an edge, press into the surface to swing around the corner.
# - Hop: standing still, hold away from the surface for HOLD_TIME to hop to one within a tile.
#
# Terms:
# - Godot's y axis points DOWN, so up is negative y (Vector2.UP is (0, -1)).
# - Normal: arrow pointing straight out of a surface.
# - Tangent: arrow pointing along a surface.
# - a.dot(b): how much two arrows point the same way (1 same, 0 sideways, -1 opposite).
# ---- Settings ----
# Speeds are positive; the direction is applied where they're used.
const GROUND_SPEED = 150.0 # Crawling on floors, walls and ceilings (pixels per second).
const AIR_SPEED = 75.0
const CLIMB_SPEED = 150.0
# Full speed in 4 frames, stopped in 6.
const GROUND_ACCEL = GROUND_SPEED / (4.0 / 60.0)
const GROUND_FRICTION = GROUND_SPEED / (6.0 / 60.0)
# Gentler steering in the air. Extra speed from leaving a surface fades slowly.
const AIR_ACCEL = 600.0
const AIR_DRAG = 300.0
const MAX_FALL_SPEED = 400.0
# A small push into the wall/ceiling each frame keeps Godot reporting that we're touching it.
const CEILING_STICK_SPEED = 20.0
const WALL_STICK_SPEED = 20.0
const SURFACE_SNAP_DISTANCE = 4.0 # Drift off a wall/ceiling by up to this and we pull back on.
# How long to hold before letting go, going over an edge, or hopping.
const HOLD_TIME = 0.5
# How close an edge must be (from our center) for an edge wrap.
@export var edgeSensorRange := 12.0
const EDGE_SENSOR_DEPTH = 4.0 # How far past our radius the sensors reach into the surface.
const WRAP_MARGIN = 0.5 # Extra gap from the corner so we don't clip into it.
const HOP_REACH = 32.0 # One tile.
const HOP_NO_CEILING_HEIGHT = 16.0 # Floor hop with nothing in reach, so you can tell it worked.
const HOP_OVERSHOOT = 2.0 # Aim slightly past the surface so we arrive with some speed and stick.
const ROTATE_TO_SURFACE_SPEED = 25.0
const MIN_LAND_SPEED = 60.0 # Slower landings don't splat.
const LAND_PITCH_MIN = 0.87
const LAND_PITCH_MAX = 1.15
# ---- State ----
# For the floor we use Godot's is_on_floor().
var isStickingToWall := false
var wallNormalX := 0.0 # -1 if the wall faces left, 1 if it faces right.
var isStickingToCeiling := false
var timeSpentUnstickingWall := 0.0
var timeSpentUnstickingCeiling := 0.0
var timeSpentHoldingEdge := 0.0
var timeSpentHoldingUpOnFloor := 0.0
# Right after wrapping onto a wall or ceiling we're usually still holding away
# from it. That shouldn't count towards letting go until it's released.
var ignoreWallUnstickUntilRelease := false
var ignoreCeilingUnstickUntilRelease := false
var wallFacingY := -1.0 # Last way we moved along a wall (-1 up). Our "facing" on walls.
var isHoppingAcross := false # No air steering mid-hop, so it lands where it was aimed.
# A wrap is a straight "entry" to the arc, a quarter-circle "arc" around the
# corner, then a straight "exit" onto the new surface.
var isWrapping := false
var wrapCorner := Vector2.ZERO
var wrapEntryStart := Vector2.ZERO
var wrapEntryLength := 0.0
var wrapFromAngle := 0.0 # Angles around the corner.
var wrapToAngle := 0.0
var wrapFromDistance := 0.0 # Distances from the corner.
var wrapToDistance := 0.0
var wrapArcLength := 0.0
var wrapExitOffset := Vector2.ZERO
var wrapFromRotation := 0.0 # Sprite rotation.
var wrapToRotation := 0.0
var wrapOntoNormal := Vector2.UP # The surface we'll end up on.
var wrapSpeed := 0.0
var wrapDistanceTravelled := 0.0
# ---- Nodes ----
# Temp for now, need to use AnimatedSprite2D later on.
@onready var sprite: Sprite2D = $Sprite2D
@onready var collisionShape: CollisionShape2D = $CollisionShape2D
# Edge-finding raycasts, one each side, under a pivot we turn to face the surface we're on.
@onready var edgeSensors: Node2D = $EdgeSensors
@onready var leftEdgeSensor: RayCast2D = $EdgeSensors/LeftEdgeSensor
@onready var rightEdgeSensor: RayCast2D = $EdgeSensors/RightEdgeSensor
# FX resources
@onready var splatParticles: CPUParticles2D = $SplatParticles
@onready var landSound: AudioStreamPlayer = $LandSound
@onready var wrapSound: AudioStreamPlayer = $WrapSound
# Placeholder sounds, see Assets/Sounds/CREDITS.txt. One plays at random per landing.
@export var landSounds: Array[AudioStream] = []
func _ready() -> void:
floor_snap_length = SURFACE_SNAP_DISTANCE
var sensorLength := _get_radius() + EDGE_SENSOR_DEPTH
leftEdgeSensor.position = Vector2(-edgeSensorRange, 0)
leftEdgeSensor.target_position = Vector2(0, sensorLength)
rightEdgeSensor.position = Vector2(edgeSensorRange, 0)
rightEdgeSensor.target_position = Vector2(0, sensorLength)
# Raycasts only ignore their parent, which is the EdgeSensors pivot, not us.
leftEdgeSensor.add_exception(self)
rightEdgeSensor.add_exception(self)
func _physics_process(delta: float) -> void:
# -1 is left/down, 1 is right/up.
var horizontalInput := Input.get_axis("moveLeft", "moveRight")
var verticalInput := Input.get_axis("moveDown", "moveUp")
if isWrapping:
_update_wrap(delta)
return
var wasInAir := _get_surface_normal() == Vector2.ZERO
if not wasInAir:
isHoppingAcross = false
if isStickingToWall and verticalInput != 0.0:
wallFacingY = -signf(verticalInput)
if _start_edge_wrap(horizontalInput, verticalInput):
return
_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()
var velocityBeforeMove := velocity
move_and_slide()
_update_wall_sticking(wasOnWall)
var climbedPastWallTop := wasOnWall and not isStickingToWall and verticalInput > 0
var tryingToLetGo := timeSpentUnstickingWall >= HOLD_TIME
if climbedPastWallTop and not tryingToLetGo and _start_wall_top_wrap():
return
_update_ceiling_sticking()
# In a corner, stick to the ceiling if pressing up, otherwise the wall.
if isStickingToWall and isStickingToCeiling:
if verticalInput > 0:
isStickingToWall = false
else:
isStickingToCeiling = false
var normal := _get_surface_normal()
var landedOnSomething := wasInAir and normal != Vector2.ZERO
if landedOnSomething:
var impactSpeed := velocityBeforeMove.dot(-normal)
if impactSpeed >= MIN_LAND_SPEED:
_splat(normal)
_update_sprite_rotation(delta)
# ---- Movement steps (in the order _physics_process runs them) ----
func _update_facing(horizontalInput: float) -> void:
if horizontalInput == 0.0:
return
if isStickingToCeiling:
sprite.flip_h = horizontalInput > 0 # Upside down, so flipped the other way.
else:
sprite.flip_h = horizontalInput < 0
func _update_vertical_movement(delta: float, horizontalInput: float, verticalInput: float) -> void:
if isStickingToCeiling:
_update_ceiling_letting_go(delta, horizontalInput, verticalInput)
elif isStickingToWall:
var targetSpeed := -CLIMB_SPEED * verticalInput
velocity.y = _accelerate(velocity.y, targetSpeed, delta)
elif not is_on_floor():
velocity.y = minf(velocity.y + get_gravity().y * delta, MAX_FALL_SPEED)
# Holding down (not moving) for HOLD_TIME lets go, hopping onto a floor if one's in reach.
func _update_ceiling_letting_go(delta: float, horizontalInput: float, verticalInput: float) -> void:
if verticalInput >= 0:
ignoreCeilingUnstickUntilRelease = false
var holdingDown := verticalInput < 0
var standingStill := horizontalInput == 0.0
if holdingDown and standingStill and not ignoreCeilingUnstickUntilRelease:
timeSpentUnstickingCeiling += delta
else:
timeSpentUnstickingCeiling = 0.0
if timeSpentUnstickingCeiling < HOLD_TIME:
velocity.y = -CEILING_STICK_SPEED
return
isStickingToCeiling = false
var floorDistance := _get_hop_distance(Vector2.DOWN)
if floorDistance >= 0.0:
velocity.y = _get_hop_speed(floorDistance)
else:
velocity.y = get_gravity().y * delta
# Holding up (not moving) for HOLD_TIME hops to the ceiling. Not against a wall,
# where up climbs it instead.
func _update_floor_hop(delta: float, horizontalInput: float, verticalInput: float) -> void:
var holdingUp := verticalInput > 0
var standingStill := horizontalInput == 0.0
if is_on_floor() and not isStickingToWall and holdingUp and standingStill:
timeSpentHoldingUpOnFloor += delta
else:
timeSpentHoldingUpOnFloor = 0.0
if timeSpentHoldingUpOnFloor >= HOLD_TIME:
timeSpentHoldingUpOnFloor = 0.0
velocity.y = -_get_hop_speed(_get_hop_height())
func _update_horizontal_movement(delta: float, horizontalInput: float, verticalInput: float) -> void:
if isStickingToWall and not is_on_floor():
_update_wall_letting_go(delta, horizontalInput, verticalInput)
return
timeSpentUnstickingWall = 0.0
if 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)
# Holding away (not climbing) for HOLD_TIME hops to the opposite wall if one's
# in reach, otherwise lets go.
func _update_wall_letting_go(delta: float, horizontalInput: float, verticalInput: float) -> void:
var pressingAwayFromWall := horizontalInput * wallNormalX > 0
if not pressingAwayFromWall:
ignoreWallUnstickUntilRelease = false
var standingStill := verticalInput == 0.0
if pressingAwayFromWall and standingStill and not ignoreWallUnstickUntilRelease:
timeSpentUnstickingWall += delta
else:
timeSpentUnstickingWall = 0.0
if timeSpentUnstickingWall < HOLD_TIME:
velocity.x = -wallNormalX * WALL_STICK_SPEED
return
var wallDistance := _get_hop_distance(Vector2(wallNormalX, 0))
if wallDistance >= 0.0:
_hop_across(wallDistance)
else:
velocity.x = horizontalInput * GROUND_SPEED
func _update_wall_sticking(wasOnWall: bool) -> void:
var meantToLetGo := timeSpentUnstickingWall >= HOLD_TIME
var driftedBackOn := false
if wasOnWall and not meantToLetGo and not is_on_wall():
driftedBackOn = _snap_to_surface(Vector2(wallNormalX, 0))
isStickingToWall = is_on_wall() or driftedBackOn
if isStickingToWall:
wallNormalX = get_wall_normal().x
func _update_ceiling_sticking() -> void:
var wasOnCeiling := isStickingToCeiling
var driftedBackOn := false
if wasOnCeiling and not is_on_ceiling():
driftedBackOn = _snap_to_surface(Vector2.DOWN)
isStickingToCeiling = is_on_ceiling() or driftedBackOn
func _update_sprite_rotation(delta: float) -> void:
var targetRotation := 0.0
if isStickingToWall and not is_on_floor():
targetRotation = PI / 2 * wallNormalX
elif isStickingToCeiling:
targetRotation = PI
# Smooth, and the same speed at any frame rate thanks to exp().
var turnAmount := 1.0 - exp(-ROTATE_TO_SURFACE_SPEED * delta)
sprite.rotation = lerp_angle(sprite.rotation, targetRotation, turnAmount)
# ---- Movement helpers ----
# GROUND_ACCEL when speeding up, GROUND_FRICTION when slowing, stopping or turning.
func _accelerate(speed: float, targetSpeed: float, delta: float) -> float:
var goingSameWay := speed == 0.0 or signf(targetSpeed) == signf(speed)
var speedingUp := targetSpeed != 0.0 and goingSameWay and absf(targetSpeed) > absf(speed)
var rate := GROUND_ACCEL if speedingUp else GROUND_FRICTION
return move_toward(speed, targetSpeed, rate * delta)
# Extra speed from leaving a surface fades slowly unless we steer against it.
func _air_steer(speed: float, horizontalInput: float, delta: float) -> float:
var targetSpeed := horizontalInput * AIR_SPEED
var steeringSameWay := horizontalInput == 0.0 or signf(horizontalInput) == signf(speed)
var hasExtraSpeed := absf(speed) > AIR_SPEED
if (hasExtraSpeed and steeringSameWay) or horizontalInput == 0.0:
return move_toward(speed, targetSpeed, AIR_DRAG * delta)
return move_toward(speed, targetSpeed, AIR_ACCEL * delta)
# Moves flush against the surface with this normal if it's within SURFACE_SNAP_DISTANCE.
func _snap_to_surface(normal: Vector2) -> bool:
var hit := move_and_collide(-normal * SURFACE_SNAP_DISTANCE, true) # true = test only, don't move.
if hit == null:
return false
# Only head-on, so catching the corner of an edge we're leaving doesn't pull us around it.
var hitHeadOn := hit.get_normal().dot(normal) >= 0.9
if not hitHeadOn:
return false
global_position += hit.get_travel()
return true
# The normal of the surface we're stuck to, or zero in the air.
func _get_surface_normal() -> Vector2:
if is_on_floor():
return Vector2.UP
if isStickingToCeiling:
return Vector2.DOWN
if isStickingToWall:
return Vector2(wallNormalX, 0)
return Vector2.ZERO
func _get_facing() -> Vector2:
if is_on_floor():
if sprite.flip_h:
return Vector2.LEFT
return Vector2.RIGHT
if isStickingToCeiling:
if sprite.flip_h:
return Vector2.RIGHT
return Vector2.LEFT
return Vector2(0, wallFacingY)
# ---- Hops ----
func _get_hop_height() -> float:
var ceilingDistance := _get_hop_distance(Vector2.UP)
if ceilingDistance >= 0.0:
return ceilingDistance
return HOP_NO_CEILING_HEIGHT
# Distance to a surface facing us within HOP_REACH (plus HOP_OVERSHOOT), or -1 if none.
func _get_hop_distance(direction: Vector2) -> float:
var hit := move_and_collide(direction * HOP_REACH, true)
if hit == null:
return -1.0
var facingUs := hit.get_normal().dot(-direction) > 0.5
if not facingUs:
return -1.0
return hit.get_travel().length() + HOP_OVERSHOOT
# Launch speed for gravity to stop us after `distance`: sqrt(2 x gravity x distance).
func _get_hop_speed(distance: float) -> float:
return sqrt(2.0 * get_gravity().y * distance)
# Sideways at crawling speed, with enough upward speed that gravity brings us
# back to the same height as we arrive.
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
# ---- Edges ----
# Pressing into the surface near an edge starts wrapping around it. A direction
# along the surface picks the side, otherwise facing does (or the other side if
# only it has an edge).
func _start_edge_wrap(horizontalInput: float, verticalInput: float) -> bool:
var normal := _get_surface_normal()
if normal == Vector2.ZERO:
return false
var inputDirection := Vector2(horizontalInput, -verticalInput) # Up is negative y.
var pressingIntoSurface := inputDirection.dot(-normal) >= 0.5
if not pressingIntoSurface:
return false
# Point the sensors into the surface. Their local +x now runs along it.
edgeSensors.rotation = normal.angle() + PI / 2
var tangent := Vector2.from_angle(edgeSensors.rotation)
var inputAlongSurface := inputDirection.dot(tangent)
if absf(inputAlongSurface) >= 0.5:
return _try_edge_wrap(normal, tangent, signf(inputAlongSurface))
var facingSide := 1.0
if _get_facing().dot(tangent) < 0:
facingSide = -1.0
if _try_edge_wrap(normal, tangent, facingSide):
return true
return _try_edge_wrap(normal, tangent, -facingSide)
# side: 1 for the sensor along the tangent, -1 for the other.
func _try_edge_wrap(normal: Vector2, tangent: Vector2, side: float) -> bool:
var sensor := leftEdgeSensor
if side > 0:
sensor = rightEdgeSensor
sensor.force_raycast_update()
if sensor.is_colliding():
return false # Still over the surface: no edge.
if not _is_point_free(sensor.global_position):
return false # Starts inside something: an inside corner, not an edge.
var direction := tangent * side
var corner = _find_edge_corner(normal, direction, edgeSensorRange + 2)
if corner == null:
return false
# Slide to the corner, swing around it, then carry on down the side so we end flat against it.
var arcEndAngle := direction.angle()
var exitOffset := -normal * _get_radius()
var arcStartAngle := normal.angle()
return _begin_wrap(corner, arcEndAngle, exitOffset, direction, arcStartAngle)
# The corner where our surface ends, if within `reach` ahead in `direction`, else null.
func _find_edge_corner(normal: Vector2, direction: Vector2, reach: float) -> Variant:
var radius := _get_radius()
var currentPosition := global_position
# 1. Find our surface with a ray from slightly behind us.
var rayStart := currentPosition - direction * radius * 0.5
var surfaceHit := _cast_ray(rayStart, rayStart - normal * radius * 2)
if surfaceHit.is_empty() or surfaceHit.normal.dot(normal) < 0.5:
return null
# 2. Find the platform's side with a ray from `reach` ahead back towards us,
# 2px inside the surface. If the surface goes on past `reach`, the ray
# starts inside it and hits nothing.
var surfacePoint: Vector2 = surfaceHit.position
var howFarAhead := (currentPosition - surfacePoint).dot(direction)
var justInsideSurface := surfacePoint - normal * 2 + direction * howFarAhead
var sideHit := _cast_ray(justInsideSurface + direction * reach, justInsideSurface - direction * radius)
if sideHit.is_empty() or sideHit.normal.dot(direction) < 0.5:
return null
var corner: Vector2 = sideHit.position + normal * 2
# 3. A real edge has empty space past it. Tile seams and the foot of a wall don't.
if not _is_point_free(corner + direction * 2 - normal * 2):
return null
return corner
# Stops us at an edge we'd cross this frame, 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()
var speedAlongSurface := velocity.dot(tangent)
if normal == Vector2.ZERO or is_zero_approx(speedAlongSurface):
timeSpentHoldingEdge = 0.0
return
var direction := tangent * signf(speedAlongSurface)
# Climbing past a wall's top swings over it instead (_start_wall_top_wrap).
var onWall := absf(normal.x) > 0.5
if onWall and direction.y < 0:
return
var distanceThisFrame := absf(speedAlongSurface) * delta
var corner = _find_edge_corner(normal, direction, distanceThisFrame + 1)
var distanceToEdge := INF
if corner != null:
distanceToEdge = (corner - global_position).dot(direction)
if distanceToEdge > distanceThisFrame:
timeSpentHoldingEdge = 0.0
return
if timeSpentHoldingEdge >= HOLD_TIME:
return
timeSpentHoldingEdge += delta
# Set our speed along the surface to stop exactly at the edge.
var speedToReachEdge := maxf(distanceToEdge, 0.0) / delta
velocity += direction * (speedToReachEdge - absf(speedAlongSurface))
# We've just climbed past a wall's top corner, so _find_edge_corner (which looks
# from the surface we're on) can't see it. Find it with our own raycasts.
func _start_wall_top_wrap() -> bool:
var wallNormal := wallNormalX
var radius := _get_radius()
var currentPosition := global_position
var aboveTop := currentPosition + Vector2(-wallNormal * (radius + 2), -radius)
var topHit := _cast_ray(aboveTop, aboveTop + Vector2(0, radius * 3))
if topHit.is_empty() or topHit.normal.y > -0.5:
return false
var topY: float = topHit.position.y
var besideWall := Vector2(currentPosition.x + wallNormal * 2, topY + 2)
var sideHit := _cast_ray(besideWall, Vector2(currentPosition.x - wallNormal * radius * 2, topY + 2))
if sideHit.is_empty() or sideHit.normal.x * wallNormal < 0.5:
return false
var corner := Vector2(sideHit.position.x, topY)
var exitOffset := Vector2(-wallNormal * radius, 0) # Onto the platform, not balanced on the corner.
return _begin_wrap(corner, Vector2.UP.angle(), exitOffset, Vector2.UP)
# ---- Edge wrap ----
# Swings around `corner` to arcEndAngle, then moves by exitOffset, ending stuck
# to the surface facing ontoNormal. With arcStartAngle, first moves straight to
# that point on the arc. Returns false if there's no room at the end.
func _begin_wrap(corner: Vector2, arcEndAngle: float, exitOffset: Vector2, ontoNormal: Vector2, arcStartAngle := NAN) -> bool:
var arcRadius := _get_radius() + WRAP_MARGIN
var endPosition := corner + Vector2.from_angle(arcEndAngle) * arcRadius + exitOffset
if not _is_spot_free(endPosition):
return false
wrapCorner = corner
wrapEntryStart = global_position
if is_nan(arcStartAngle): # NAN ("not a number") means it wasn't given.
var fromCorner := global_position - corner
wrapFromAngle = fromCorner.angle()
wrapFromDistance = fromCorner.length()
wrapEntryLength = 0.0
else:
wrapFromAngle = arcStartAngle
wrapFromDistance = arcRadius
var arcStart := corner + Vector2.from_angle(arcStartAngle) * arcRadius
wrapEntryLength = global_position.distance_to(arcStart)
wrapToAngle = arcEndAngle
wrapToDistance = arcRadius
wrapArcLength = absf(angle_difference(wrapFromAngle, wrapToAngle)) * arcRadius # Angle x radius.
wrapExitOffset = exitOffset
wrapFromRotation = sprite.rotation
wrapToRotation = ontoNormal.angle() + PI / 2
wrapOntoNormal = ontoNormal
wrapDistanceTravelled = 0.0
wrapSpeed = minf(velocity.length(), GROUND_SPEED) # Keep our speed going in.
velocity = Vector2.ZERO
isWrapping = true
wrapSound.play()
return true
func _update_wrap(delta: float) -> void:
wrapSpeed = move_toward(wrapSpeed, GROUND_SPEED, GROUND_ACCEL * delta)
var totalLength := wrapEntryLength + wrapArcLength + wrapExitOffset.length()
wrapDistanceTravelled = minf(wrapDistanceTravelled + wrapSpeed * delta, totalLength)
# Entry.
var distance := wrapDistanceTravelled
if distance < wrapEntryLength:
var arcStart := wrapCorner + Vector2.from_angle(wrapFromAngle) * wrapFromDistance
global_position = wrapEntryStart.lerp(arcStart, distance / wrapEntryLength)
return
distance -= wrapEntryLength
# Arc. Progress goes from 0 to 1.
var arcProgress := 1.0
if wrapArcLength > 0.0:
arcProgress = minf(distance / wrapArcLength, 1.0)
var angle := lerp_angle(wrapFromAngle, wrapToAngle, arcProgress)
var distanceFromCorner := lerpf(wrapFromDistance, wrapToDistance, arcProgress)
var positionOnArc := wrapCorner + Vector2.from_angle(angle) * distanceFromCorner
sprite.rotation = lerp_angle(wrapFromRotation, wrapToRotation, arcProgress)
# Exit.
var exitProgress := 0.0
if wrapExitOffset != Vector2.ZERO:
exitProgress = maxf(distance - wrapArcLength, 0.0) / wrapExitOffset.length()
global_position = positionOnArc + wrapExitOffset * exitProgress
if wrapDistanceTravelled >= totalLength:
_finish_wrap(delta)
func _finish_wrap(delta: float) -> void:
# Close the WRAP_MARGIN gap with move_and_slide() so is_on_floor()/is_on_wall()
# describe where we are now, not where we were before the wrap.
velocity = -wrapOntoNormal * (WRAP_MARGIN + 1) / delta
# Godot still thinks we're on the floor we started from, so it would snap us
# down to it and count the wall as floor (floor_block_on_wall). Turn both off
# for this move unless we're ending on a floor.
var endingOnFloor := wrapOntoNormal == Vector2.UP
var savedFloorSnap := floor_snap_length
var savedBlockOnWall := floor_block_on_wall
if not endingOnFloor:
floor_snap_length = 0.0
floor_block_on_wall = false
move_and_slide()
floor_snap_length = savedFloorSnap
floor_block_on_wall = savedBlockOnWall
# Keep our speed along the new surface so leaving the wrap isn't a sudden stop.
var exitDirection: Vector2
if wrapExitOffset != Vector2.ZERO:
exitDirection = wrapExitOffset.normalized()
else:
exitDirection = Vector2.from_angle(wrapToAngle).orthogonal()
velocity = exitDirection * wrapSpeed
isWrapping = false
isStickingToCeiling = wrapOntoNormal.y > 0.5
isStickingToWall = absf(wrapOntoNormal.x) > 0.5
if isStickingToWall:
wallNormalX = wrapOntoNormal.x
ignoreWallUnstickUntilRelease = true
ignoreCeilingUnstickUntilRelease = isStickingToCeiling
# ---- Effects ----
func _splat(normal: Vector2) -> void:
splatParticles.global_position = global_position - normal * _get_radius()
splatParticles.reset_physics_interpolation() # A jump, not movement: don't smooth from the last spot.
splatParticles.direction = normal
splatParticles.restart()
if not landSounds.is_empty():
landSound.stream = landSounds.pick_random()
landSound.pitch_scale = randf_range(LAND_PITCH_MIN, LAND_PITCH_MAX)
landSound.play()
# ---- Physics queries (all ignore the slime itself) ----
func _get_radius() -> float:
return (collisionShape.shape as CircleShape2D).radius
# Returns the hit (.position, .normal), or an empty Dictionary if nothing.
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()
# Whether our whole shape fits at this spot.
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()