Compare commits

..

No commits in common. "bec85cefe3f255031cd239e5c3dba01d920b4f4b" and "e5bdc85293cd1a1592c1b474f1d616304c28e128" have entirely different histories.

View file

@ -1,143 +1,132 @@
extends CharacterBody2D extends CharacterBody2D
# The slime crawls on floors, walls and ceilings and sticks to them. # ---- Movement ----
# - Let go: hold away from a wall or ceiling for HOLD_TIME. # All speeds are positive amounts; the direction is applied where they're used.
# - Edge hold: crawling to an edge stops there until you've held towards it for HOLD_TIME. const GROUND_SPEED = 150.0 # Crawling speed on floors, walls and ceilings.
# - 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 AIR_SPEED = 75.0
const CLIMB_SPEED = 150.0 const CLIMB_SPEED = 150.0 # Up and down a wall.
# Full speed in 4 frames, stopped in 6. # Acceleration on floors, walls and ceilings. Full speed in 4 frames, stopped in 6.
const GROUND_ACCEL = GROUND_SPEED / (4.0 / 60.0) const GROUND_ACCEL = GROUND_SPEED / (4.0 / 60.0)
const GROUND_FRICTION = GROUND_SPEED / (6.0 / 60.0) const GROUND_FRICTION = GROUND_SPEED / (6.0 / 60.0)
# In the air we steer more gently, and keep any extra speed we had when we left
# Gentler steering in the air. Extra speed from leaving a surface fades slowly. # a surface instead of snapping down to AIR_SPEED.
const AIR_ACCEL = 600.0 const AIR_ACCEL = 600.0
const AIR_DRAG = 300.0 const AIR_DRAG = 300.0
const MAX_FALL_SPEED = 400.0 const MAX_FALL_SPEED = 400.0
# A small push into the wall/ceiling each frame keeps Godot reporting that we're touching it. # ---- Sticking to walls and ceilings ----
const CEILING_STICK_SPEED = 20.0 const CEILING_STICK_SPEED = 20.0 # Small push up that keeps the slime pressed against the ceiling.
const WALL_STICK_SPEED = 20.0 const WALL_STICK_SPEED = 20.0 # Small push into the wall that keeps the slime pressed against it.
const SURFACE_SNAP_DISTANCE = 4.0 # Drift off a wall/ceiling by up to this and we pull back on. # 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 before letting go, going over an edge, or hopping. # 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,
# and hopping.
const HOLD_TIME = 0.5 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 isStickingToWall := false
var wallNormalX := 0.0 # -1 if the wall faces left, 1 if it faces right. var wallNormalX := 0.0 # Which way the wall we're on faces (-1 left, 1 right).
var isStickingToCeiling := false
var timeSpentUnstickingWall := 0.0 var timeSpentUnstickingWall := 0.0
var isStickingToCeiling := false
var timeSpentUnstickingCeiling := 0.0 var timeSpentUnstickingCeiling := 0.0
var timeSpentHoldingEdge := 0.0 # Right after wrapping onto a wall we're usually still holding away from it,
var timeSpentHoldingUpOnFloor := 0.0 # so don't count that towards unsticking until the direction is released.
# 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 ignoreWallUnstickUntilRelease := false
# Same for down after wrapping onto a ceiling (e.g. crawling down a wall and under).
var ignoreCeilingUnstickUntilRelease := false var ignoreCeilingUnstickUntilRelease := false
var wallFacingY := -1.0 # Last way we moved along a wall (-1 up). Our "facing" on walls. # ---- Surface edges ----
var isHoppingAcross := false # No air steering mid-hop, so it lands where it was aimed. # 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
# A wrap is a straight "entry" to the arc, a quarter-circle "arc" around the # ---- Edge wrapping ----
# corner, then a straight "exit" onto the new surface. # 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 isWrapping := false
var wrapCorner := Vector2.ZERO var wrapCorner := Vector2.ZERO
var wrapEntryStart := Vector2.ZERO var wrapEntryStart := Vector2.ZERO # Where a straight move before the arc starts from.
var wrapEntryLength := 0.0 var wrapEntryLength := 0.0
var wrapFromAngle := 0.0 # Angles around the corner. var wrapFromAngle := 0.0
var wrapToAngle := 0.0 var wrapToAngle := 0.0
var wrapFromDistance := 0.0 # Distances from the corner. var wrapFromDistance := 0.0
var wrapToDistance := 0.0 var wrapToDistance := 0.0
var wrapArcLength := 0.0 var wrapArcLength := 0.0
var wrapExitOffset := Vector2.ZERO var wrapExitOffset := Vector2.ZERO # Straight move after the arc, onto the new surface.
var wrapFromRotation := 0.0 # Sprite rotation. var wrapFromRotation := 0.0
var wrapToRotation := 0.0 var wrapToRotation := 0.0
var wrapOntoNormal := Vector2.UP # The surface we'll end up on. var wrapOntoNormal := Vector2.UP # Normal of the surface we end up on.
var wrapSpeed := 0.0 var wrapSpeed := 0.0 # Eases up to GROUND_SPEED, so starting from a standstill isn't a jolt.
var wrapDistanceTravelled := 0.0 var wrapTravelled := 0.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.
# ---- Nodes ---- # ---- 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. # Temp for now, need to use AnimatedSprite2D later on.
@onready var sprite: Sprite2D = $Sprite2D @onready var sprite: Sprite2D = $Sprite2D
@onready var collisionShape: CollisionShape2D = $CollisionShape2D @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 edgeSensors: Node2D = $EdgeSensors
@onready var leftEdgeSensor: RayCast2D = $EdgeSensors/LeftEdgeSensor @onready var leftEdgeSensor: RayCast2D = $EdgeSensors/LeftEdgeSensor
@onready var rightEdgeSensor: RayCast2D = $EdgeSensors/RightEdgeSensor @onready var rightEdgeSensor: RayCast2D = $EdgeSensors/RightEdgeSensor
# FX resources
@onready var splatParticles: CPUParticles2D = $SplatParticles @onready var splatParticles: CPUParticles2D = $SplatParticles
@onready var landSound: AudioStreamPlayer = $LandSound @onready var landSound: AudioStreamPlayer = $LandSound
@onready var wrapSound: AudioStreamPlayer = $WrapSound @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: func _ready() -> void:
floor_snap_length = SURFACE_SNAP_DISTANCE floor_snap_length = SURFACE_SNAP_DISTANCE
var sensorDepth := _get_radius() + EDGE_SENSOR_DEPTH
var sensorLength := _get_radius() + EDGE_SENSOR_DEPTH
leftEdgeSensor.position = Vector2(-edgeSensorRange, 0) leftEdgeSensor.position = Vector2(-edgeSensorRange, 0)
leftEdgeSensor.target_position = Vector2(0, sensorLength) leftEdgeSensor.target_position = Vector2(0, sensorDepth)
rightEdgeSensor.position = Vector2(edgeSensorRange, 0) rightEdgeSensor.position = Vector2(edgeSensorRange, 0)
rightEdgeSensor.target_position = Vector2(0, sensorLength) rightEdgeSensor.target_position = Vector2(0, sensorDepth)
# The sensors' parent is the EdgeSensors pivot, so exclude_parent doesn't
# Raycasts only ignore their parent, which is the EdgeSensors pivot, not us. # cover us. Without this they can hit our own collider.
leftEdgeSensor.add_exception(self) leftEdgeSensor.add_exception(self)
rightEdgeSensor.add_exception(self) rightEdgeSensor.add_exception(self)
func _physics_process(delta: float) -> void: func _physics_process(delta: float) -> void:
# -1 is left/down, 1 is right/up.
var horizontalInput := Input.get_axis("moveLeft", "moveRight") var horizontalInput := Input.get_axis("moveLeft", "moveRight")
var verticalInput := Input.get_axis("moveDown", "moveUp") var verticalInput := Input.get_axis("moveDown", "moveUp")
# Swinging around a corner, ignore everything else until we're done.
if isWrapping: if isWrapping:
_update_wrap(delta) _update_wrap(delta)
return return
var wasInAir := _get_surface_normal() == Vector2.ZERO var wasInAir := _get_surface_normal() == Vector2.ZERO
if not wasInAir: if not wasInAir: isHoppingAcross = false
isHoppingAcross = false
if isStickingToWall and verticalInput != 0.0: # Near the edge of a surface and pressing into it: wrap over onto the
wallFacingY = -signf(verticalInput) # side of the platform.
if isStickingToWall and verticalInput: wallFacingY = -signf(verticalInput)
if _start_edge_wrap(horizontalInput, verticalInput): if _start_edge_wrap(horizontalInput, verticalInput):
return return
@ -153,94 +142,79 @@ func _physics_process(delta: float) -> void:
move_and_slide() move_and_slide()
_update_wall_sticking(wasOnWall) _update_wall_sticking(wasOnWall)
# Climbed past the top of a wall: swing over onto the floor on top.
var climbedPastWallTop := wasOnWall and not isStickingToWall and verticalInput > 0 if wasOnWall and not isStickingToWall and verticalInput > 0 \
var tryingToLetGo := timeSpentUnstickingWall >= HOLD_TIME and timeSpentUnstickingWall < HOLD_TIME and _start_wall_top_wrap():
if climbedPastWallTop and not tryingToLetGo and _start_wall_top_wrap():
return return
_update_ceiling_sticking() _update_ceiling_sticking()
# In a corner, stick to the ceiling if pressing up, otherwise the wall. # 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 isStickingToWall and isStickingToCeiling:
if verticalInput > 0: if verticalInput > 0: isStickingToWall = false
isStickingToWall = false else: isStickingToCeiling = false
else:
isStickingToCeiling = false
# Just landed on something: squish.
var normal := _get_surface_normal() var normal := _get_surface_normal()
var landedOnSomething := wasInAir and normal != Vector2.ZERO if wasInAir and normal != Vector2.ZERO and velocityBeforeMove.dot(-normal) >= MIN_LAND_SPEED:
if landedOnSomething: _splat(normal)
var impactSpeed := velocityBeforeMove.dot(-normal)
if impactSpeed >= MIN_LAND_SPEED:
_splat(normal)
_update_sprite_rotation(delta) _update_sprite_rotation(delta)
# ---- Movement steps (in the order _physics_process runs them) ---- # ---- Movement steps (in the order _physics_process runs them) ----
# 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: func _update_facing(horizontalInput: float) -> void:
if horizontalInput == 0.0: if not horizontalInput: return
return if isStickingToCeiling: sprite.flip_h = horizontalInput > 0
if isStickingToCeiling: else: sprite.flip_h = horizontalInput < 0
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: func _update_vertical_movement(delta: float, horizontalInput: float, verticalInput: float) -> void:
if isStickingToCeiling: if isStickingToCeiling:
_update_ceiling_letting_go(delta, horizontalInput, verticalInput) # 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: elif isStickingToWall:
var targetSpeed := -CLIMB_SPEED * verticalInput velocity.y = _accelerate(velocity.y, -CLIMB_SPEED * verticalInput, delta)
velocity.y = _accelerate(velocity.y, targetSpeed, delta)
elif not is_on_floor(): elif not is_on_floor():
velocity.y = minf(velocity.y + get_gravity().y * delta, MAX_FALL_SPEED) 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
# Holding down (not moving) for HOLD_TIME lets go, hopping onto a floor if one's in reach. # ceiling above. Not against a wall though, where up climbs it instead.
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: func _update_floor_hop(delta: float, horizontalInput: float, verticalInput: float) -> void:
var holdingUp := verticalInput > 0 if is_on_floor() and not isStickingToWall and verticalInput > 0 and not horizontalInput:
var standingStill := horizontalInput == 0.0
if is_on_floor() and not isStickingToWall and holdingUp and standingStill:
timeSpentHoldingUpOnFloor += delta timeSpentHoldingUpOnFloor += delta
else: else: timeSpentHoldingUpOnFloor = 0.0
timeSpentHoldingUpOnFloor = 0.0
if timeSpentHoldingUpOnFloor >= HOLD_TIME: if timeSpentHoldingUpOnFloor >= HOLD_TIME:
timeSpentHoldingUpOnFloor = 0.0 timeSpentHoldingUpOnFloor = 0.0
velocity.y = -_get_hop_speed(_get_hop_height()) velocity.y = -sqrt(2.0 * get_gravity().y * _get_hop_height())
func _update_horizontal_movement(delta: float, horizontalInput: float, verticalInput: float) -> void: 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(): if isStickingToWall and not is_on_floor():
_update_wall_letting_go(delta, horizontalInput, verticalInput) 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 return
timeSpentUnstickingWall = 0.0 timeSpentUnstickingWall = 0.0
@ -249,387 +223,267 @@ func _update_horizontal_movement(delta: float, horizontalInput: float, verticalI
elif not isHoppingAcross: elif not isHoppingAcross:
velocity.x = _air_steer(velocity.x, horizontalInput, delta) velocity.x = _air_steer(velocity.x, horizontalInput, delta)
# After moving: are we still on the wall? If we drifted slightly off it (and
# Holding away (not climbing) for HOLD_TIME hops to the opposite wall if one's # aren't trying to let go), pull back onto it instead of falling off.
# 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: func _update_wall_sticking(wasOnWall: bool) -> void:
var meantToLetGo := timeSpentUnstickingWall >= HOLD_TIME isStickingToWall = is_on_wall() or (wasOnWall and timeSpentUnstickingWall < HOLD_TIME \
var driftedBackOn := false and _snap_to_surface(Vector2(wallNormalX, 0)))
if wasOnWall and not meantToLetGo and not is_on_wall(): if isStickingToWall: wallNormalX = get_wall_normal().x
driftedBackOn = _snap_to_surface(Vector2(wallNormalX, 0))
isStickingToWall = is_on_wall() or driftedBackOn
if isStickingToWall:
wallNormalX = get_wall_normal().x
# After moving: are we still on the ceiling? If we drifted slightly off it,
# pull back onto it instead of falling off.
func _update_ceiling_sticking() -> void: func _update_ceiling_sticking() -> void:
var wasOnCeiling := isStickingToCeiling var wasOnCeiling := isStickingToCeiling
var driftedBackOn := false isStickingToCeiling = is_on_ceiling() or (wasOnCeiling and _snap_to_surface(Vector2.DOWN))
if wasOnCeiling and not is_on_ceiling():
driftedBackOn = _snap_to_surface(Vector2.DOWN)
isStickingToCeiling = is_on_ceiling() or driftedBackOn
# 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: func _update_sprite_rotation(delta: float) -> void:
var targetRotation := 0.0 # In a corner only one of these is ever true (decided in _physics_process).
if isStickingToWall and not is_on_floor(): var target := 0.0
targetRotation = PI / 2 * wallNormalX if not is_on_floor() and isStickingToWall: target = PI/2 * wallNormalX
elif isStickingToCeiling: elif isStickingToCeiling: target = PI
targetRotation = 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))
# 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 ---- # ---- Movement helpers ----
# GROUND_ACCEL when speeding up, GROUND_FRICTION when slowing, stopping or turning. # Moves speed towards target: GROUND_ACCEL when speeding up, GROUND_FRICTION
func _accelerate(speed: float, targetSpeed: float, delta: float) -> float: # when slowing down or stopping.
var goingSameWay := speed == 0.0 or signf(targetSpeed) == signf(speed) func _accelerate(speed: float, target: float, delta: float) -> float:
var speedingUp := targetSpeed != 0.0 and goingSameWay and absf(targetSpeed) > absf(speed) var speedingUp := target != 0.0 and (speed == 0.0 or signf(target) == signf(speed)) and absf(target) > absf(speed)
var rate := GROUND_ACCEL if speedingUp else GROUND_FRICTION return move_toward(speed, target, (GROUND_ACCEL if speedingUp else GROUND_FRICTION) * delta)
return move_toward(speed, targetSpeed, rate * delta)
# Horizontal steering in the air. Extra speed from leaving a surface fades
# Extra speed from leaving a surface fades slowly unless we steer against it. # slowly unless we steer against it.
func _air_steer(speed: float, horizontalInput: float, delta: float) -> float: func _air_steer(speed: float, horizontalInput: float, delta: float) -> float:
var targetSpeed := horizontalInput * AIR_SPEED var target := horizontalInput * AIR_SPEED
var steeringSameWay := horizontalInput == 0.0 or signf(horizontalInput) == signf(speed) var keepingMomentum := absf(speed) > AIR_SPEED and (horizontalInput == 0.0 or signf(horizontalInput) == signf(speed))
var hasExtraSpeed := absf(speed) > AIR_SPEED if keepingMomentum or horizontalInput == 0.0:
if (hasExtraSpeed and steeringSameWay) or horizontalInput == 0.0: return move_toward(speed, target, AIR_DRAG * delta)
return move_toward(speed, targetSpeed, AIR_DRAG * delta) return move_toward(speed, target, AIR_ACCEL * delta)
return move_toward(speed, targetSpeed, AIR_ACCEL * delta)
# If the surface with this normal is within SURFACE_SNAP_DISTANCE, move flush
# Moves flush against the surface with this normal if it's within SURFACE_SNAP_DISTANCE. # 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: func _snap_to_surface(normal: Vector2) -> bool:
var hit := move_and_collide(-normal * SURFACE_SNAP_DISTANCE, true) # true = test only, don't move. var hit := move_and_collide(-normal * SURFACE_SNAP_DISTANCE, true)
if hit == null: if not hit or hit.get_normal().dot(normal) < 0.9: return false
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() global_position += hit.get_travel()
return true return true
# Normal of the surface we're stuck to, or zero if we're in the air.
# The normal of the surface we're stuck to, or zero in the air.
func _get_surface_normal() -> Vector2: func _get_surface_normal() -> Vector2:
if is_on_floor(): if is_on_floor(): return Vector2.UP
return Vector2.UP if isStickingToCeiling: return Vector2.DOWN
if isStickingToCeiling: if isStickingToWall: return Vector2(wallNormalX, 0)
return Vector2.DOWN
if isStickingToWall:
return Vector2(wallNormalX, 0)
return Vector2.ZERO return Vector2.ZERO
# Which way the slime is facing, in world space.
func _get_facing() -> Vector2: func _get_facing() -> Vector2:
if is_on_floor(): if is_on_floor(): return Vector2(-1 if sprite.flip_h else 1, 0)
if sprite.flip_h: if isStickingToCeiling: return Vector2(1 if sprite.flip_h else -1, 0)
return Vector2.LEFT
return Vector2.RIGHT
if isStickingToCeiling:
if sprite.flip_h:
return Vector2.RIGHT
return Vector2.LEFT
return Vector2(0, wallFacingY) return Vector2(0, wallFacingY)
# ---- Hops ---- # ---- 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: func _get_hop_height() -> float:
var ceilingDistance := _get_hop_distance(Vector2.UP) var distance := _get_hop_distance(Vector2.UP)
if ceilingDistance >= 0.0: return distance if distance >= 0.0 else HOP_NO_CEILING_HEIGHT
return ceilingDistance
return HOP_NO_CEILING_HEIGHT
# How far to hop in direction to reach a surface facing us within HOP_REACH
# Distance to a surface facing us within HOP_REACH (plus HOP_OVERSHOOT), or -1 if none. # (plus HOP_OVERSHOOT), or -1 if there isn't one.
func _get_hop_distance(direction: Vector2) -> float: func _get_hop_distance(direction: Vector2) -> float:
var hit := move_and_collide(direction * HOP_REACH, true) var hit := move_and_collide(direction * HOP_REACH, true)
if hit == null: if hit and hit.get_normal().dot(-direction) > 0.5:
return -1.0 return hit.get_travel().length() + HOP_OVERSHOOT
var facingUs := hit.get_normal().dot(-direction) > 0.5 return -1.0
if not facingUs:
return -1.0
return hit.get_travel().length() + HOP_OVERSHOOT
# Hops from the wall we're on to the one distance away opposite, at crawling
# Launch speed for gravity to stop us after `distance`: sqrt(2 x gravity x distance). # speed, on an arc that lands at the same height we left from.
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: func _hop_across(distance: float) -> void:
var flightTime := distance / GROUND_SPEED var flightTime := distance / GROUND_SPEED
velocity.x = wallNormalX * GROUND_SPEED velocity.x = wallNormalX * GROUND_SPEED
velocity.y = -0.5 * get_gravity().y * flightTime velocity.y = -0.5 * get_gravity().y * flightTime
isHoppingAcross = true isHoppingAcross = true
# ---- Surface edges ----
# ---- Edges ---- # Pressing into the surface we're on: if there's an edge in range, slide to it
# and wrap over onto the side of the platform. Holding a direction along the
# Pressing into the surface near an edge starts wrapping around it. A direction # surface picks that side, otherwise we go the way we're facing, or the other
# along the surface picks the side, otherwise facing does (or the other side if # way if only that side has an edge.
# only it has an edge).
func _start_edge_wrap(horizontalInput: float, verticalInput: float) -> bool: func _start_edge_wrap(horizontalInput: float, verticalInput: float) -> bool:
var normal := _get_surface_normal() var normal := _get_surface_normal()
if normal == Vector2.ZERO: if normal == Vector2.ZERO: return false
return false var input := Vector2(horizontalInput, -verticalInput)
if input.dot(-normal) < 0.5: return false
var inputDirection := Vector2(horizontalInput, -verticalInput) # Up is negative y. # Point the sensors into the surface. Their local +x runs along it.
var pressingIntoSurface := inputDirection.dot(-normal) >= 0.5 edgeSensors.rotation = normal.angle() + PI/2
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 tangent := Vector2.from_angle(edgeSensors.rotation)
var along := input.dot(tangent)
if absf(along) >= 0.5:
return _try_edge_wrap(normal, tangent, signf(along))
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)
var inputAlongSurface := inputDirection.dot(tangent) # Tries wrapping over the edge on one side (side is -1 or 1 along 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: func _try_edge_wrap(normal: Vector2, tangent: Vector2, side: float) -> bool:
var sensor := leftEdgeSensor var sensor := rightEdgeSensor if side > 0 else leftEdgeSensor
if side > 0:
sensor = rightEdgeSensor
sensor.force_raycast_update() sensor.force_raycast_update()
if sensor.is_colliding(): if sensor.is_colliding(): return false
return false # Still over the surface: no edge. # A sensor starting inside something is an inside corner, not an edge.
if not _is_point_free(sensor.global_position): if not _is_point_free(sensor.global_position): return false
return false # Starts inside something: an inside corner, not an edge.
var direction := tangent * side var direction := tangent * side
var corner = _find_edge_corner(normal, direction, edgeSensorRange + 2) var corner = _find_edge_corner(normal, direction, edgeSensorRange + 2)
if corner == null: if corner == null: return false
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, direction.angle(), -normal * _get_radius(), direction, normal.angle())
# Slide to the corner, swing around it, then carry on down the side so we end flat against it. # Finds the corner where the surface we're on (facing normal) ends, up to reach
var arcEndAngle := direction.angle() # ahead of us in direction. Returns null if there's no edge that close.
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: func _find_edge_corner(normal: Vector2, direction: Vector2, reach: float) -> Variant:
var radius := _get_radius() var radius := _get_radius()
var currentPosition := global_position var pos := global_position
# The surface we're on, checked from the side away from the edge.
# 1. Find our surface with a ray from slightly behind us. var surfaceFrom := pos - direction * radius * 0.5
var rayStart := currentPosition - direction * radius * 0.5 var surfaceHit := _cast_ray(surfaceFrom, surfaceFrom - normal * radius * 2)
var surfaceHit := _cast_ray(rayStart, rayStart - normal * radius * 2) if not surfaceHit or surfaceHit.normal.dot(normal) < 0.5: return null
if surfaceHit.is_empty() or surfaceHit.normal.dot(normal) < 0.5: # Side of the platform, just inside its surface, looking back from reach
return null # ahead. If the surface carries on past reach, the ray starts inside it
# and finds nothing.
# 2. Find the platform's side with a ray from `reach` ahead back towards us, var line: Vector2 = surfaceHit.position - normal * 2 + direction * (pos - surfaceHit.position).dot(direction)
# 2px inside the surface. If the surface goes on past `reach`, the ray var faceHit := _cast_ray(line + direction * reach, line - direction * radius)
# starts inside it and hits nothing. if not faceHit or faceHit.normal.dot(direction) < 0.5: return null
var surfacePoint: Vector2 = surfaceHit.position var corner: Vector2 = faceHit.position + normal * 2
var howFarAhead := (currentPosition - surfacePoint).dot(direction) # A real edge has empty space just past it, behind the surface. Seams
var justInsideSurface := surfacePoint - normal * 2 + direction * howFarAhead # between tiles (and the foot of a wall) have solid there, so they're not edges.
var sideHit := _cast_ray(justInsideSurface + direction * reach, justInsideSurface - direction * radius) if not _is_point_free(corner + direction * 2 - normal * 2): return null
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 return corner
# If this frame's movement along the surface would take us past its edge, stop
# Stops us at an edge we'd cross this frame, until we've held towards it for HOLD_TIME. # at the edge instead, until we've held towards it for HOLD_TIME.
func _hold_at_edge(delta: float) -> void: func _hold_at_edge(delta: float) -> void:
var normal := _get_surface_normal() var normal := _get_surface_normal()
var tangent := normal.orthogonal() var tangent := normal.orthogonal()
var speedAlongSurface := velocity.dot(tangent) var speed := velocity.dot(tangent)
if normal == Vector2.ZERO or is_zero_approx(speedAlongSurface): if normal == Vector2.ZERO or is_zero_approx(speed):
timeSpentHoldingEdge = 0.0 timeSpentHoldingEdge = 0.0
return return
var direction := tangent * signf(speed)
var direction := tangent * signf(speedAlongSurface) # Climbing up past the top of a wall swings over onto it instead.
# Climbing past a wall's top swings over it instead (_start_wall_top_wrap). if absf(normal.x) > 0.5 and direction.y < 0: return
var onWall := absf(normal.x) > 0.5 var step := absf(speed) * delta
if onWall and direction.y < 0: var corner = _find_edge_corner(normal, direction, step + 1)
return var distanceToEdge: float = INF if corner == null else (corner - global_position).dot(direction)
if distanceToEdge > step:
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 timeSpentHoldingEdge = 0.0
return return
# Held long enough: let go and carry on over the edge.
if timeSpentHoldingEdge >= HOLD_TIME: if timeSpentHoldingEdge >= HOLD_TIME: return
return
timeSpentHoldingEdge += delta timeSpentHoldingEdge += delta
velocity += direction * (maxf(distanceToEdge, 0.0) / delta - absf(speed))
# Set our speed along the surface to stop exactly at the edge. # Just climbed past the top of a wall: find the corner and swing up on top.
var speedToReachEdge := maxf(distanceToEdge, 0.0) / delta # (By now we've already passed the corner, so _find_edge_corner, which looks
velocity += direction * (speedToReachEdge - absf(speedAlongSurface)) # from the surface we're still on, can't see it. Hence the separate raycasts.)
# 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: func _start_wall_top_wrap() -> bool:
var wallNormal := wallNormalX var wallNormal := wallNormalX
var radius := _get_radius() var radius := _get_radius()
var currentPosition := global_position var pos := global_position
# Top of the platform, just past the wall.
var aboveTop := currentPosition + Vector2(-wallNormal * (radius + 2), -radius) var topHit := _cast_ray(pos + Vector2(-wallNormal * (radius + 2), -radius), pos + Vector2(-wallNormal * (radius + 2), radius * 2))
var topHit := _cast_ray(aboveTop, aboveTop + Vector2(0, radius * 3)) if not topHit or topHit.normal.y > -0.5: return false
if topHit.is_empty() or topHit.normal.y > -0.5:
return false
var topY: float = topHit.position.y 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)
var besideWall := Vector2(currentPosition.x + wallNormal * 2, topY + 2) # ---- Edge wrapping ----
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
# Starts swinging around corner to toAngle from it, then moving by exitOffset,
# ending up stuck to the surface facing ontoNormal.
# If fromAngle is given, first moves straight to that point on the arc,
# otherwise the arc starts from where we are now.
# Returns false if there's no room to end up there.
func _begin_wrap(corner: Vector2, toAngle: float, exitOffset: Vector2, ontoNormal: Vector2, fromAngle := NAN) -> bool:
var radius := _get_radius() + WRAP_MARGIN
if not _is_spot_free(corner + Vector2.from_angle(toAngle) * radius + exitOffset): return false
var offset := global_position - corner
wrapCorner = corner wrapCorner = corner
wrapEntryStart = global_position wrapEntryStart = global_position
if is_nan(arcStartAngle): # NAN ("not a number") means it wasn't given. if is_nan(fromAngle):
var fromCorner := global_position - corner wrapFromAngle = offset.angle()
wrapFromAngle = fromCorner.angle() wrapFromDistance = offset.length()
wrapFromDistance = fromCorner.length()
wrapEntryLength = 0.0 wrapEntryLength = 0.0
else: else:
wrapFromAngle = arcStartAngle wrapFromAngle = fromAngle
wrapFromDistance = arcRadius wrapFromDistance = radius
var arcStart := corner + Vector2.from_angle(arcStartAngle) * arcRadius wrapEntryLength = global_position.distance_to(corner + Vector2.from_angle(fromAngle) * radius)
wrapEntryLength = global_position.distance_to(arcStart) wrapToAngle = toAngle
wrapToAngle = arcEndAngle wrapToDistance = radius
wrapToDistance = arcRadius wrapArcLength = absf(angle_difference(wrapFromAngle, wrapToAngle)) * radius
wrapArcLength = absf(angle_difference(wrapFromAngle, wrapToAngle)) * arcRadius # Angle x radius.
wrapExitOffset = exitOffset wrapExitOffset = exitOffset
wrapFromRotation = sprite.rotation wrapFromRotation = sprite.rotation
wrapToRotation = ontoNormal.angle() + PI / 2 wrapToRotation = ontoNormal.angle() + PI/2
wrapOntoNormal = ontoNormal wrapOntoNormal = ontoNormal
wrapTravelled = 0.0
wrapDistanceTravelled = 0.0 # Start at the speed we were already going, so crawling into a wrap is seamless.
wrapSpeed = minf(velocity.length(), GROUND_SPEED) # Keep our speed going in. wrapSpeed = minf(velocity.length(), GROUND_SPEED)
velocity = Vector2.ZERO velocity = Vector2.ZERO
isWrapping = true isWrapping = true
wrapSound.play() wrapSound.play()
return true return true
func _update_wrap(delta: float) -> void: func _update_wrap(delta: float) -> void:
# Speed up to crawling speed like we would on a surface.
wrapSpeed = move_toward(wrapSpeed, GROUND_SPEED, GROUND_ACCEL * delta) wrapSpeed = move_toward(wrapSpeed, GROUND_SPEED, GROUND_ACCEL * delta)
var totalLength := wrapEntryLength + wrapArcLength + wrapExitOffset.length() var totalLength := wrapEntryLength + wrapArcLength + wrapExitOffset.length()
wrapDistanceTravelled = minf(wrapDistanceTravelled + wrapSpeed * delta, totalLength) wrapTravelled = minf(wrapTravelled + wrapSpeed * delta, totalLength)
# The distance travelled is split between the straight entry, the arc and
# Entry. # the straight exit by their lengths.
var distance := wrapDistanceTravelled var travelled := wrapTravelled
if distance < wrapEntryLength: var arcStart := wrapCorner + Vector2.from_angle(wrapFromAngle) * wrapFromDistance
var arcStart := wrapCorner + Vector2.from_angle(wrapFromAngle) * wrapFromDistance if travelled < wrapEntryLength:
global_position = wrapEntryStart.lerp(arcStart, distance / wrapEntryLength) global_position = wrapEntryStart.lerp(arcStart, travelled / wrapEntryLength)
return return
distance -= wrapEntryLength travelled -= wrapEntryLength
var arcProgress := 1.0 if wrapArcLength <= 0.0 else minf(travelled / wrapArcLength, 1.0)
# Arc. Progress goes from 0 to 1. var exitProgress := 0.0 if wrapExitOffset == Vector2.ZERO \
var arcProgress := 1.0 else maxf(travelled - wrapArcLength, 0.0) / wrapExitOffset.length()
if wrapArcLength > 0.0:
arcProgress = minf(distance / wrapArcLength, 1.0)
var angle := lerp_angle(wrapFromAngle, wrapToAngle, arcProgress) var angle := lerp_angle(wrapFromAngle, wrapToAngle, arcProgress)
var distanceFromCorner := lerpf(wrapFromDistance, wrapToDistance, arcProgress) var distance := lerpf(wrapFromDistance, wrapToDistance, arcProgress)
var positionOnArc := wrapCorner + Vector2.from_angle(angle) * distanceFromCorner global_position = wrapCorner + Vector2.from_angle(angle) * distance + wrapExitOffset * exitProgress
sprite.rotation = lerp_angle(wrapFromRotation, wrapToRotation, arcProgress) sprite.rotation = lerp_angle(wrapFromRotation, wrapToRotation, arcProgress)
if wrapTravelled < totalLength: return
# Exit. _finish_wrap(delta)
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: func _finish_wrap(delta: float) -> void:
# Close the WRAP_MARGIN gap with move_and_slide() so is_on_floor()/is_on_wall() # Close the small gap left by WRAP_MARGIN so we're touching the new surface.
# describe where we are now, not where we were before the wrap. # 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.
velocity = -wrapOntoNormal * (WRAP_MARGIN + 1) / delta velocity = -wrapOntoNormal * (WRAP_MARGIN + 1) / delta
# Godot still thinks we're on whatever floor we were on before the wrap, so
# Godot still thinks we're on the floor we started from, so it would snap us # it would try to snap us down onto it, and (floor_block_on_wall) count the
# down to it and count the wall as floor (floor_block_on_wall). Turn both off # wall we're pushing into as floor. Only allow that if we're ending on a floor.
# for this move unless we're ending on a floor.
var endingOnFloor := wrapOntoNormal == Vector2.UP var endingOnFloor := wrapOntoNormal == Vector2.UP
var savedFloorSnap := floor_snap_length var floorSnap := floor_snap_length
var savedBlockOnWall := floor_block_on_wall var blockOnWall := floor_block_on_wall
if not endingOnFloor: if not endingOnFloor:
floor_snap_length = 0.0 floor_snap_length = 0.0
floor_block_on_wall = false floor_block_on_wall = false
move_and_slide() move_and_slide()
floor_snap_length = savedFloorSnap floor_snap_length = floorSnap
floor_block_on_wall = savedBlockOnWall floor_block_on_wall = blockOnWall
# Carry on at the same speed along the new surface, so leaving the wrap
# Keep our speed along the new surface so leaving the wrap isn't a sudden stop. # isn't a sudden stop. Normal movement then speeds up or slows down from here.
var exitDirection: Vector2 var exitDirection := wrapExitOffset.normalized() if wrapExitOffset != Vector2.ZERO \
if wrapExitOffset != Vector2.ZERO: else Vector2.from_angle(wrapToAngle).orthogonal()
exitDirection = wrapExitOffset.normalized()
else:
exitDirection = Vector2.from_angle(wrapToAngle).orthogonal()
velocity = exitDirection * wrapSpeed velocity = exitDirection * wrapSpeed
isWrapping = false isWrapping = false
@ -640,33 +494,29 @@ func _finish_wrap(delta: float) -> void:
ignoreWallUnstickUntilRelease = true ignoreWallUnstickUntilRelease = true
ignoreCeilingUnstickUntilRelease = isStickingToCeiling ignoreCeilingUnstickUntilRelease = isStickingToCeiling
# ---- Effects ---- # ---- Effects ----
# Squish sound and a little burst of slime where we hit the surface.
func _splat(normal: Vector2) -> void: func _splat(normal: Vector2) -> void:
splatParticles.global_position = global_position - normal * _get_radius() splatParticles.global_position = global_position - normal * _get_radius()
splatParticles.reset_physics_interpolation() # A jump, not movement: don't smooth from the last spot. # 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.direction = normal
splatParticles.restart() splatParticles.restart()
if landSounds:
if not landSounds.is_empty():
landSound.stream = landSounds.pick_random() landSound.stream = landSounds.pick_random()
landSound.pitch_scale = randf_range(LAND_PITCH_MIN, LAND_PITCH_MAX) landSound.pitch_scale = randf_range(LAND_PITCH_MIN, LAND_PITCH_MAX)
landSound.play() landSound.play()
# ---- Physics queries ----
# ---- Physics queries (all ignore the slime itself) ----
func _get_radius() -> float: func _get_radius() -> float:
return (collisionShape.shape as CircleShape2D).radius 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: func _cast_ray(from: Vector2, to: Vector2) -> Dictionary:
var query := PhysicsRayQueryParameters2D.create(from, to, collision_mask, [get_rid()]) var query := PhysicsRayQueryParameters2D.create(from, to, collision_mask, [get_rid()])
return get_world_2d().direct_space_state.intersect_ray(query) return get_world_2d().direct_space_state.intersect_ray(query)
func _is_point_free(point: Vector2) -> bool: func _is_point_free(point: Vector2) -> bool:
var query := PhysicsPointQueryParameters2D.new() var query := PhysicsPointQueryParameters2D.new()
query.position = point query.position = point
@ -674,8 +524,6 @@ func _is_point_free(point: Vector2) -> bool:
query.exclude = [get_rid()] query.exclude = [get_rid()]
return get_world_2d().direct_space_state.intersect_point(query, 1).is_empty() 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: func _is_spot_free(spot: Vector2) -> bool:
var query := PhysicsShapeQueryParameters2D.new() var query := PhysicsShapeQueryParameters2D.new()
query.shape = collisionShape.shape query.shape = collisionShape.shape