1358 lines
54 KiB
GDScript
Executable file
1358 lines
54 KiB
GDScript
Executable file
extends CharacterBody2D
|
|
|
|
# The slime crawls on floors, walls and ceilings and sticks to them.
|
|
# Generally the player press away from a surface while holding still to unstick.
|
|
|
|
###############
|
|
## Constants ##
|
|
###############
|
|
const GROUND_SPEED = 150.0
|
|
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 or hopping.
|
|
const HOLD_TIME = 0.33
|
|
# How long to hold towards an edge we've stopped at before going over it.
|
|
# 0 never stops us at edges at all.
|
|
const EDGE_HOLD_TIME = 0.1
|
|
|
|
# How close an edge must be (from our center) for an edge wrap.
|
|
const EDGE_SENSOR_RANGE := 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.
|
|
# Where we stop short of an edge, from our center: with the leading sensor just
|
|
# past it, so the sprite's side lines up with the edge and the sensor reads "no surface".
|
|
const EDGE_STOP_DISTANCE = EDGE_SENSOR_RANGE - 0.5
|
|
|
|
const HOP_REACH = 32.0
|
|
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_FOR_SPLAT = 60.0
|
|
const LAND_PITCH_MIN = 0.87
|
|
const LAND_PITCH_MAX = 1.15
|
|
|
|
# Tubes are tiles too narrow for us, tagged in their TileSet with which sides are
|
|
# open (the "tube_openings" custom data). Holding into a tube's mouth squeezes us
|
|
# in as pixels. An ordinary tube streams us through to the other end
|
|
# (PixelStream). A manual one ("tube_manual" tiles) lets the player steer us
|
|
# through it, round corners and either way at crossings (TubeSteer).
|
|
# A one-way one ("tube_one_way" tiles) is an ordinary tube we can only go into
|
|
# at its entrance, and whose air pulls us in there and blows us away from its
|
|
# exit (OneWayTube, TubeAirCurrents).
|
|
const TUBE_DATA_LAYER = "tube_openings"
|
|
const TUBE_OPEN_UP = 1
|
|
const TUBE_OPEN_RIGHT = 2
|
|
const TUBE_OPEN_DOWN = 4
|
|
const TUBE_OPEN_LEFT = 8
|
|
const TUBE_WIDTH = 6.0 # The channel drawn through the tiles in LevelTiles.png.
|
|
# The longest our pixels stretch in a tube (two tiles). They bunch up to fit.
|
|
const TUBE_MAX_FLOW_LENGTH = 64.0
|
|
const TUBE_ENTRY_REACH = 2.0 # How close our side must be to a tube mouth to go in.
|
|
const TUBE_REENTRY_DELAY = 0.3 # So we don't dive straight back in.
|
|
const TUBE_ENTER_HOLD_TIME = 0.35 # How long to press into a mouth before we squeeze in.
|
|
# How straight into a mouth we must press (dot product with the way in; 0.9 is
|
|
# within about 25 degrees). Diagonals don't count, so they can climb walls instead.
|
|
const TUBE_ENTER_MIN_ALIGNMENT = 0.9
|
|
const REST_FRAME = 0 # The Idle animation's frame. We reform as it.
|
|
# The PressWall animation's frame: squashed against a wall on its left. Its flat
|
|
# side is further from our center than our radius, so it's drawn this much away
|
|
# from the wall to sit flush against it (see _align_press_wall_sprite). It shows
|
|
# while pushing into a wall from the floor or the ceiling (upside down), or into
|
|
# a tube mouth in one.
|
|
const PRESS_WALL_FRAME = 9
|
|
const PRESS_WALL_SPRITE_SHIFT = 6.0
|
|
|
|
# Holding away from a surface with another facing it one tile across makes us
|
|
# stretch between the two (a bridge) instead of hopping: wall to wall, or floor
|
|
# to ceiling. The Bridge and BridgeVertical animations' frames are columns
|
|
# exactly that long, always drawn the same way round and centred between the
|
|
# surfaces (see _align_press_wall_sprite).
|
|
const BRIDGE_FRAME = 10 # Wall to wall. Drawn upright, so it's turned a quarter.
|
|
# Wall to wall, leaning towards the wall we're holding towards. Drawn upright
|
|
# and turned like BRIDGE_FRAME, so the frame's top ends up on the right.
|
|
const BRIDGE_LEAN_RIGHT_FRAME = 11 # Most of us bunched at the top.
|
|
const BRIDGE_LEAN_LEFT_FRAME = 12 # Most of us bunched at the bottom.
|
|
const BRIDGE_VERTICAL_FRAME = 13 # Floor to ceiling.
|
|
# Floor to ceiling, leaning towards the surface we're holding towards: most of
|
|
# us down on the floor, or up on the ceiling.
|
|
const BRIDGE_VERTICAL_DOWN_FRAME = 14
|
|
const BRIDGE_VERTICAL_UP_FRAME = 15
|
|
const BRIDGE_GAP = 32.0 # One tile.
|
|
const BRIDGE_GAP_TOLERANCE = 1.5
|
|
# How long we show the plain bridge frame after attaching before leaning towards
|
|
# the surface we're holding towards.
|
|
const BRIDGE_SETTLE_TIME = 0.15
|
|
const IN_AIR_FRAME = 8 # The InAir animation's frame.
|
|
|
|
###############
|
|
## Variables ##
|
|
###############
|
|
var isStickingToWall := false
|
|
var wallNormalX := 0.0
|
|
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. Everything else about the
|
|
# path is worked out from these (see the _wrap_... helpers).
|
|
var isWrapping := false
|
|
var wrapCorner := Vector2.ZERO
|
|
var wrapFromNormal := Vector2.UP # The surface we're leaving.
|
|
var wrapOntoNormal := Vector2.UP # The surface we'll end up on.
|
|
var wrapEntryStart := Vector2.ZERO # Where we were when the wrap started.
|
|
var wrapArcStartAngle := 0.0 # Angle around the corner where the arc begins.
|
|
var wrapSpeed := 0.0
|
|
var wrapDistanceTravelled := 0.0
|
|
|
|
# The sprite's rotation turns smoothly, but it's only drawn at quarter turns so
|
|
# its pixels stay square (see _set_sprite_rotation).
|
|
var smoothSpriteRotation := 0.0
|
|
|
|
# Read by the AnimationTree's state machine. Set in _update_animation_conditions.
|
|
var isOnSurface := false
|
|
var isCrawling := false # Moving along the surface we're on.
|
|
var isHoldingAtEdge := false
|
|
var isPressingIntoSurface := false
|
|
var isPressingWall := false # On the floor or ceiling, pushing sideways into a wall or a tube mouth in one.
|
|
# On the ceiling in a corner, the wall there (its normal's x), or 0. We stay on
|
|
# the ceiling pushing into it; holding down moves us onto it.
|
|
var ceilingWallNormalX := 0.0
|
|
var spriteBasePosition := Vector2.ZERO # The Sprite2D's position as set in the scene.
|
|
var isReachingAway := false # Holding away from the surface, counting towards letting go/hopping.
|
|
var isSqueezingIntoTube := false # Holding into a tube's mouth, about to go in.
|
|
var tubeSqueezeDirection := Vector2.ZERO # Which way into that mouth.
|
|
|
|
var isInTube := false
|
|
var tubePixels: PixelStream # Our pixels streaming through an ordinary tube, or null.
|
|
# Our pixels being steered through a manual tube, or null.
|
|
var tubeSteer: TubeSteer = null
|
|
var tubeExitPose := {} # Where the stream comes out (see _tube_exit_pose).
|
|
var tubeReentryCooldown := 0.0
|
|
var timeSpentSqueezingIntoTube := 0.0
|
|
var tubeLayers: Array[TileMapLayer] = [] # TileMapLayers whose tiles can be tubes.
|
|
var hasFoundTubeLayers := false
|
|
|
|
# Stretched across a one-tile gap between two walls, or a floor and a ceiling.
|
|
# We're stuck to neither as far as the rest of the movement code knows; holding
|
|
# towards one for HOLD_TIME lets go of the other (see _update_bridge).
|
|
var isBridging := false
|
|
var bridgeAxis := Vector2.RIGHT # RIGHT between walls, DOWN between floor and ceiling.
|
|
var bridgeHoldSide := 0.0 # Which way along bridgeAxis we're holding (1, -1), or 0.
|
|
var timeSpentLeavingBridge := 0.0
|
|
var timeSpentDroppingFromBridge := 0.0
|
|
# Between floor and ceiling, which one we're holding towards: -1 up, 1 down, or 0.
|
|
# Read by the AnimationTree to lean the column that way.
|
|
var bridgeLean := 0
|
|
var bridgeSettleTimeLeft := 0.0 # Until this runs out we don't lean (see BRIDGE_SETTLE_TIME).
|
|
|
|
var carriedItem: CarryItem = null # The item riding in our center, or null. Tubes drop it.
|
|
|
|
###########
|
|
## Nodes ##
|
|
###########
|
|
@onready var sprite: Sprite2D = $Sprite2D
|
|
@onready var animationTree: AnimationTree = $AnimationTree
|
|
@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] = []
|
|
|
|
# The circle that marks where you're steering from in a manual tube (TubeSteer).
|
|
@export_group("Tube Indicator")
|
|
@export var tubeIndicatorColor := Color(1.0, 0.85, 0.3)
|
|
@export var tubeIndicatorBorderColor := Color.WHITE
|
|
@export_range(1.0, 12.0, 0.5) var tubeIndicatorRadius := 4.0
|
|
@export_group("")
|
|
|
|
|
|
func _ready() -> void:
|
|
floor_snap_length = SURFACE_SNAP_DISTANCE
|
|
|
|
var sensorLength := _get_radius() + EDGE_SENSOR_DEPTH
|
|
leftEdgeSensor.position = Vector2(-EDGE_SENSOR_RANGE, 0)
|
|
leftEdgeSensor.target_position = Vector2(0, sensorLength)
|
|
rightEdgeSensor.position = Vector2(EDGE_SENSOR_RANGE, 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)
|
|
|
|
spriteBasePosition = sprite.position
|
|
animationTree.mixer_applied.connect(_align_press_wall_sprite)
|
|
|
|
# Shifts the PressWall frame away from the wall. Done here rather than with a
|
|
# track in the animation because which way depends on flip_h, and keyed off the
|
|
# frame shown so it can't get out of step with the animation.
|
|
# It moves the sprite rather than its offset: the tube effects build the slime
|
|
# they reform as from the sprite's offset, and that must not carry the shift.
|
|
func _align_press_wall_sprite() -> void:
|
|
var targetPosition := spriteBasePosition
|
|
if sprite.frame in [BRIDGE_FRAME, BRIDGE_LEAN_RIGHT_FRAME, BRIDGE_LEAN_LEFT_FRAME, BRIDGE_VERTICAL_FRAME, BRIDGE_VERTICAL_DOWN_FRAME, BRIDGE_VERTICAL_UP_FRAME]:
|
|
# The sprite's offset lifts it off the surface we're on. Undo that so the
|
|
# column sits centred on us, between the surfaces.
|
|
targetPosition -= sprite.offset.rotated(sprite.rotation).round()
|
|
elif sprite.frame == PRESS_WALL_FRAME:
|
|
# Towards the frame's right (away from its wall), turned with the sprite.
|
|
var awayFromWall := Vector2(-1.0 if sprite.flip_h else 1.0, 0.0).rotated(sprite.rotation).round()
|
|
targetPosition += awayFromWall * PRESS_WALL_SPRITE_SHIFT
|
|
if sprite.position != targetPosition:
|
|
sprite.position = targetPosition
|
|
sprite.reset_physics_interpolation() # A different pose, not movement.
|
|
|
|
func _physics_process(delta: float) -> void:
|
|
# Note: Up is positive y.
|
|
var moveInput := Vector2(Input.get_axis("moveLeft", "moveRight"), Input.get_axis("moveDown", "moveUp"))
|
|
|
|
if isInTube:
|
|
_update_tube(delta, moveInput)
|
|
return
|
|
if isWrapping:
|
|
_update_wrap(delta)
|
|
return
|
|
if isBridging:
|
|
_update_bridge(delta, moveInput)
|
|
return
|
|
tubeReentryCooldown = maxf(tubeReentryCooldown - delta, 0.0)
|
|
|
|
var wasInAir := (_get_surface_normal() == Vector2.ZERO)
|
|
if not wasInAir:
|
|
isHoppingAcross = false
|
|
|
|
if isStickingToWall and moveInput.y != 0.0:
|
|
wallFacingY = -signf(moveInput.y)
|
|
if _update_tube_squeeze(delta, moveInput):
|
|
return
|
|
if _start_edge_wrap(moveInput):
|
|
return
|
|
|
|
# Animated Sprite
|
|
_update_facing(moveInput)
|
|
_update_animation_conditions(moveInput)
|
|
|
|
_update_vertical_movement(delta, moveInput)
|
|
_update_floor_hop(delta, moveInput)
|
|
_update_horizontal_movement(delta, moveInput)
|
|
if isBridging: # Just started one.
|
|
return
|
|
_hold_at_edge(delta)
|
|
|
|
var wasOnWall := (isStickingToWall and not is_on_floor())
|
|
var wasOnCeiling := isStickingToCeiling
|
|
var velocityBeforeMove := velocity
|
|
|
|
move_and_slide()
|
|
|
|
_update_wall_sticking(wasOnWall)
|
|
|
|
var climbedPastWallTop := wasOnWall and not isStickingToWall and moveInput.y > 0
|
|
var tryingToLetGo := timeSpentUnstickingWall >= HOLD_TIME
|
|
if climbedPastWallTop and not tryingToLetGo and _start_wall_top_wrap():
|
|
return
|
|
|
|
_update_ceiling_sticking()
|
|
_pick_corner_surface(moveInput, wasOnCeiling)
|
|
|
|
var normal := _get_surface_normal()
|
|
var landedOnSomething := wasInAir and normal != Vector2.ZERO
|
|
if landedOnSomething:
|
|
var impactSpeed := velocityBeforeMove.dot(-normal)
|
|
if impactSpeed >= MIN_LAND_SPEED_FOR_SPLAT:
|
|
_splat(normal)
|
|
|
|
_update_sprite_rotation(delta)
|
|
|
|
# ---- Movement steps (in the order _physics_process runs them) ----
|
|
|
|
func _update_facing(moveInput: Vector2) -> void:
|
|
if moveInput == Vector2.ZERO:
|
|
return
|
|
var pressedWallDirection := _get_pressed_wall_direction(moveInput)
|
|
if pressedWallDirection != Vector2.ZERO:
|
|
# The PressWall frame has its wall on the left: flip it to face the way we
|
|
# press, however the sprite is turned for the surface we're on.
|
|
var frameLeft := Vector2.LEFT.rotated(_rotation_for(_get_surface_normal()))
|
|
sprite.flip_h = frameLeft.dot(pressedWallDirection) < 0
|
|
elif isStickingToCeiling:
|
|
sprite.flip_h = moveInput.x > 0 # Upside down, so flipped the other way.
|
|
elif isStickingToWall:
|
|
if wallNormalX < 0: sprite.flip_h = moveInput.y < 0
|
|
else: sprite.flip_h = moveInput.y > 0
|
|
else:
|
|
sprite.flip_h = moveInput.x < 0
|
|
|
|
# Facts the AnimationTree's state machine reads to pick an animation (see the
|
|
# transitions' advance expressions in player.tscn).
|
|
func _update_animation_conditions(moveInput: Vector2) -> void:
|
|
if isBridging:
|
|
# Only "not isBridging" leaves the Bridge state, but keep the rest quiet anyway.
|
|
isOnSurface = true
|
|
isCrawling = false
|
|
isHoldingAtEdge = false
|
|
isPressingIntoSurface = false
|
|
isPressingWall = false
|
|
isReachingAway = false
|
|
return
|
|
isOnSurface = _get_surface_normal() != Vector2.ZERO
|
|
isPressingWall = _get_pressed_wall_direction(moveInput) != Vector2.ZERO
|
|
isCrawling = ((moveInput.x != 0.0 and (isStickingToCeiling or is_on_floor()))
|
|
or (moveInput.y != 0.0 and isStickingToWall)) and not isSqueezingIntoTube and not isPressingWall
|
|
isHoldingAtEdge = timeSpentHoldingEdge > 0
|
|
isPressingIntoSurface = (_is_pressing_into_surface(moveInput) or isSqueezingIntoTube) and not isPressingWall
|
|
isReachingAway = ((is_on_floor() and timeSpentHoldingUpOnFloor > 0)
|
|
or (isStickingToCeiling and timeSpentUnstickingCeiling > 0)
|
|
or (isStickingToWall and timeSpentUnstickingWall > 0))
|
|
|
|
func _update_vertical_movement(delta: float, moveInput: Vector2) -> void:
|
|
if isStickingToCeiling:
|
|
_update_ceiling_letting_go(delta, moveInput)
|
|
elif isStickingToWall:
|
|
var targetSpeed := -CLIMB_SPEED * moveInput.y
|
|
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, moveInput: Vector2) -> void:
|
|
if moveInput.y >= 0:
|
|
ignoreCeilingUnstickUntilRelease = false
|
|
|
|
var holdingDown := moveInput.y < 0
|
|
var standingStill := moveInput.x == 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
|
|
|
|
if _try_begin_bridge(Vector2.DOWN):
|
|
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
|
|
|
|
# Hopping from the floop while holding still.
|
|
func _update_floor_hop(delta: float, moveInput: Vector2) -> void:
|
|
if is_on_floor() and not isStickingToWall and moveInput.x == 0.0 and moveInput.y > 0:
|
|
timeSpentHoldingUpOnFloor += delta
|
|
else:
|
|
timeSpentHoldingUpOnFloor = 0.0
|
|
|
|
if timeSpentHoldingUpOnFloor >= HOLD_TIME:
|
|
timeSpentHoldingUpOnFloor = 0.0
|
|
if _try_begin_bridge(Vector2.UP):
|
|
return
|
|
velocity.y = -_get_hop_speed(_get_hop_height())
|
|
|
|
func _update_horizontal_movement(delta: float, moveInput: Vector2) -> void:
|
|
if isStickingToWall and not is_on_floor():
|
|
_update_wall_letting_go(delta, moveInput)
|
|
return
|
|
|
|
timeSpentUnstickingWall = 0.0
|
|
if is_on_floor() or isStickingToCeiling:
|
|
velocity.x = _accelerate(velocity.x, moveInput.x * GROUND_SPEED, delta)
|
|
elif not isHoppingAcross:
|
|
velocity.x = _air_steer(velocity.x, moveInput.x, delta)
|
|
|
|
# Holding away (not climbing) for HOLD_TIME bridges to the opposite wall if it's
|
|
# one tile across, hops to it if it's further but in reach, otherwise lets go.
|
|
func _update_wall_letting_go(delta: float, moveInput: Vector2) -> void:
|
|
var pressingAwayFromWall := moveInput.x * wallNormalX > 0
|
|
if not pressingAwayFromWall:
|
|
ignoreWallUnstickUntilRelease = false
|
|
|
|
var standingStill := moveInput.y == 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
|
|
|
|
if _try_begin_bridge(Vector2(wallNormalX, 0)):
|
|
return
|
|
|
|
var wallDistance := _get_hop_distance(Vector2(wallNormalX, 0))
|
|
if wallDistance >= 0.0:
|
|
_hop_across(wallDistance)
|
|
else:
|
|
velocity.x = moveInput.x * 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
|
|
|
|
# In a ceiling corner: holding up takes the ceiling and holding down the wall.
|
|
# Otherwise we stay on the one we were on, so crawling along the ceiling into a
|
|
# wall leaves us pressed against it (the PressWall pose), and climbing a wall
|
|
# into the corner leaves us on the wall.
|
|
func _pick_corner_surface(moveInput: Vector2, wasOnCeiling: bool) -> void:
|
|
ceilingWallNormalX = 0.0
|
|
# A down still held from steering out of a tube in the ceiling doesn't count
|
|
# (see ignoreCeilingUnstickUntilRelease): we stay where the tube put us.
|
|
var holdingDown := moveInput.y < 0 and not ignoreCeilingUnstickUntilRelease
|
|
# Physics only reports a wall while we move into it, so holding straight down
|
|
# beside one needs a look.
|
|
if isStickingToCeiling and not isStickingToWall and holdingDown:
|
|
var side := _get_touching_wall_side()
|
|
if side != 0.0:
|
|
isStickingToWall = true
|
|
wallNormalX = -side
|
|
if not (isStickingToWall and isStickingToCeiling):
|
|
return
|
|
if holdingDown:
|
|
isStickingToCeiling = false
|
|
timeSpentUnstickingCeiling = 0.0
|
|
elif moveInput.y > 0 or wasOnCeiling:
|
|
isStickingToWall = false
|
|
ceilingWallNormalX = wallNormalX
|
|
else:
|
|
isStickingToCeiling = false
|
|
|
|
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)
|
|
_set_sprite_rotation(lerp_angle(smoothSpriteRotation, targetRotation, turnAmount))
|
|
|
|
# Rotated pixel art gets jagged and uneven, so draw the sprite at the nearest
|
|
# quarter turn. On a wrap it flips over halfway round the corner.
|
|
func _set_sprite_rotation(angle: float) -> void:
|
|
smoothSpriteRotation = angle
|
|
var snapped := snappedf(angle, PI / 2)
|
|
if is_equal_approx(snapped, sprite.rotation):
|
|
return
|
|
sprite.rotation = snapped
|
|
# Physics interpolation would otherwise tween through the angles in between.
|
|
sprite.reset_physics_interpolation()
|
|
|
|
# ---- 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, xInput: float, delta: float) -> float:
|
|
var targetSpeed := xInput * AIR_SPEED
|
|
var steeringSameWay := xInput == 0.0 or signf(xInput) == signf(speed)
|
|
var hasExtraSpeed := absf(speed) > AIR_SPEED
|
|
if (hasExtraSpeed and steeringSameWay) or xInput == 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
|
|
|
|
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
|
|
|
|
# True when the input points (within a couple of degrees) straight into the
|
|
# surface the slime is stuck to. moveInput is y-up, so flip it to Godot's y-down.
|
|
func _is_pressing_into_surface(moveInput: Vector2) -> bool:
|
|
var normal := _get_surface_normal()
|
|
if normal == Vector2.ZERO or moveInput == Vector2.ZERO:
|
|
return false
|
|
var inputDir := Vector2(moveInput.x, -moveInput.y)
|
|
return absf(inputDir.angle_to(-normal)) < deg_to_rad(2)
|
|
|
|
# Which way the surface we're pushing into is, when it's square to the one we're
|
|
# on (the PressWall pose), or Vector2.ZERO:
|
|
# - From the floor or ceiling, a wall, or a tube mouth in one. Holding up into a
|
|
# wall from the floor climbs it instead.
|
|
# - From a wall, a tube mouth in the floor or ceiling.
|
|
func _get_pressed_wall_direction(moveInput: Vector2) -> Vector2:
|
|
if isSqueezingIntoTube:
|
|
# Not into a mouth in the surface we're on: that's the Crouch pose.
|
|
var isSquare := absf(tubeSqueezeDirection.dot(_get_surface_normal())) < 0.5
|
|
return tubeSqueezeDirection if isSquare else Vector2.ZERO
|
|
if isStickingToCeiling:
|
|
# Holding down into it moves us onto the wall instead (see _pick_corner_surface).
|
|
if moveInput.x * ceilingWallNormalX < 0 and moveInput.y >= 0.0:
|
|
return Vector2(-ceilingWallNormalX, 0.0)
|
|
return Vector2.ZERO
|
|
if is_on_floor() and isStickingToWall and moveInput.x * wallNormalX < 0 and moveInput.y <= 0.0:
|
|
return Vector2(-wallNormalX, 0.0)
|
|
return Vector2.ZERO
|
|
|
|
# Which side a wall is right up against us (1 right, -1 left), or 0.
|
|
func _get_touching_wall_side() -> float:
|
|
var collision := KinematicCollision2D.new()
|
|
for side: float in [1.0, -1.0]:
|
|
if test_move(global_transform, Vector2(side, 0), collision) and absf(collision.get_normal().x) > 0.7:
|
|
return side
|
|
return 0.0
|
|
|
|
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
|
|
|
|
|
|
# ---- Bridges ----
|
|
|
|
# Bridges from the surface we're on (facing `normal`) to one facing it
|
|
# BRIDGE_GAP across, if there is one. Returns whether it did.
|
|
func _try_begin_bridge(normal: Vector2) -> bool:
|
|
var surfaces := _find_bridge_surfaces(normal)
|
|
if surfaces.is_empty():
|
|
return false
|
|
_begin_bridge(normal, surfaces.own, surfaces.other)
|
|
return true
|
|
|
|
|
|
# Where the surface we're on (facing `normal`) and the one across from it are,
|
|
# if that's BRIDGE_GAP away and faces us all across our width: {own, other}
|
|
# (points on each). Otherwise empty.
|
|
func _find_bridge_surfaces(normal: Vector2) -> Dictionary:
|
|
var reach := BRIDGE_GAP + BRIDGE_GAP_TOLERANCE
|
|
var across := normal.orthogonal()
|
|
var radius := _get_radius()
|
|
var surfaces := {}
|
|
for offset: float in [-radius * 0.5, 0.0, radius * 0.5]:
|
|
var from := global_position + across * offset
|
|
var ownHit := _cast_ray(from, from - normal * reach)
|
|
var otherHit := _cast_ray(from, from + normal * reach)
|
|
if ownHit.is_empty() or otherHit.is_empty():
|
|
return {}
|
|
if ownHit.normal.dot(normal) < 0.9 or otherHit.normal.dot(-normal) < 0.9:
|
|
return {}
|
|
var gap := absf((otherHit.position - ownHit.position).dot(normal))
|
|
if absf(gap - BRIDGE_GAP) > BRIDGE_GAP_TOLERANCE:
|
|
return {}
|
|
surfaces = {own = ownHit.position, other = otherHit.position}
|
|
return surfaces
|
|
|
|
|
|
func _begin_bridge(normal: Vector2, ownPoint: Vector2, otherPoint: Vector2) -> void:
|
|
isBridging = true
|
|
bridgeAxis = Vector2.RIGHT if absf(normal.x) > 0.5 else Vector2.DOWN
|
|
isStickingToWall = false
|
|
isStickingToCeiling = false
|
|
isHoppingAcross = false
|
|
timeSpentUnstickingWall = 0.0
|
|
timeSpentUnstickingCeiling = 0.0
|
|
timeSpentHoldingUpOnFloor = 0.0
|
|
timeSpentHoldingEdge = 0.0
|
|
timeSpentLeavingBridge = 0.0
|
|
timeSpentDroppingFromBridge = 0.0
|
|
# We're still holding away from the surface we left, towards the one across.
|
|
# Keep holding and we cross over to it after HOLD_TIME, like any other hold.
|
|
bridgeHoldSide = signf(normal.dot(bridgeAxis))
|
|
bridgeSettleTimeLeft = BRIDGE_SETTLE_TIME
|
|
_update_bridge_lean()
|
|
velocity = Vector2.ZERO
|
|
|
|
# Halfway between the surfaces, staying put the other way.
|
|
var middle := (ownPoint + otherPoint) / 2.0
|
|
global_position += bridgeAxis * (middle - global_position).dot(bridgeAxis)
|
|
_show_bridge_pose()
|
|
|
|
|
|
# Shows the bridge frame for bridgeAxis and bridgeLean, turned to suit.
|
|
# Always drawn the same way round, whichever surface we came from, unflipped.
|
|
func _show_bridge_pose() -> void:
|
|
sprite.flip_h = false
|
|
if bridgeAxis == Vector2.RIGHT:
|
|
# Turned as for the left wall, which puts the frame's flat side on top
|
|
# and its top on the right.
|
|
_set_sprite_rotation(_rotation_for(Vector2.RIGHT))
|
|
if bridgeLean < 0:
|
|
_show_pose(&"BridgeLeanLeft", BRIDGE_LEAN_LEFT_FRAME)
|
|
elif bridgeLean > 0:
|
|
_show_pose(&"BridgeLeanRight", BRIDGE_LEAN_RIGHT_FRAME)
|
|
else:
|
|
_show_pose(&"Bridge", BRIDGE_FRAME)
|
|
else:
|
|
# Upright.
|
|
_set_sprite_rotation(0.0)
|
|
if bridgeLean < 0:
|
|
_show_pose(&"BridgeVerticalUp", BRIDGE_VERTICAL_UP_FRAME)
|
|
elif bridgeLean > 0:
|
|
_show_pose(&"BridgeVerticalDown", BRIDGE_VERTICAL_DOWN_FRAME)
|
|
else:
|
|
_show_pose(&"BridgeVertical", BRIDGE_VERTICAL_FRAME)
|
|
|
|
|
|
# Holding towards either surface for HOLD_TIME sticks us to it and lets go of
|
|
# the other: left or right between walls, up or down between floor and ceiling.
|
|
# Holding down between walls, or left or right between floor and ceiling, for
|
|
# HOLD_TIME lets go of both and drops us. Diagonals do neither.
|
|
func _update_bridge(delta: float, moveInput: Vector2) -> void:
|
|
velocity = Vector2.ZERO
|
|
var inputDirection := Vector2(moveInput.x, -moveInput.y) # Up is negative y.
|
|
var along := signf(inputDirection.dot(bridgeAxis))
|
|
var across := signf(inputDirection.dot(bridgeAxis.orthogonal()))
|
|
|
|
var side := along if across == 0.0 else 0.0
|
|
if side != 0.0 and side == bridgeHoldSide:
|
|
timeSpentLeavingBridge += delta
|
|
else:
|
|
timeSpentLeavingBridge = 0.0
|
|
bridgeHoldSide = side
|
|
bridgeSettleTimeLeft = maxf(bridgeSettleTimeLeft - delta, 0.0)
|
|
var previousLean := bridgeLean
|
|
_update_bridge_lean()
|
|
if bridgeLean != previousLean:
|
|
_show_bridge_pose() # The frame and its turn change together.
|
|
|
|
# Between walls only down drops us (bridgeAxis.orthogonal() is up there).
|
|
var holdingToDrop := along == 0.0 and across != 0.0
|
|
if bridgeAxis == Vector2.RIGHT:
|
|
holdingToDrop = holdingToDrop and inputDirection.y > 0.0
|
|
if holdingToDrop:
|
|
timeSpentDroppingFromBridge += delta
|
|
else:
|
|
timeSpentDroppingFromBridge = 0.0
|
|
|
|
if timeSpentLeavingBridge >= HOLD_TIME:
|
|
_leave_bridge(bridgeAxis * side, delta)
|
|
elif timeSpentDroppingFromBridge >= HOLD_TIME:
|
|
_drop_from_bridge()
|
|
|
|
|
|
# Leans the column towards the surface we're holding towards. The hold side is
|
|
# along bridgeAxis: -1 left, 1 right between walls; -1 up, 1 down between floor
|
|
# and ceiling. Straight for a moment after attaching (BRIDGE_SETTLE_TIME).
|
|
func _update_bridge_lean() -> void:
|
|
bridgeLean = 0 if bridgeSettleTimeLeft > 0.0 else int(bridgeHoldSide)
|
|
|
|
|
|
# Lets go of both surfaces and falls from where we are.
|
|
func _drop_from_bridge() -> void:
|
|
isBridging = false
|
|
timeSpentLeavingBridge = 0.0
|
|
timeSpentDroppingFromBridge = 0.0
|
|
velocity = Vector2.ZERO
|
|
# is_on_floor() and friends still describe where we bridged from. A move on
|
|
# the spot brings them up to date, so we don't count as on it.
|
|
move_and_slide()
|
|
_set_sprite_rotation(0.0)
|
|
_show_pose(&"InAir", IN_AIR_FRAME)
|
|
|
|
|
|
# Sticks to the surface in `direction` from us.
|
|
func _leave_bridge(direction: Vector2, delta: float) -> void:
|
|
isBridging = false
|
|
timeSpentLeavingBridge = 0.0
|
|
timeSpentDroppingFromBridge = 0.0
|
|
var normal := -direction
|
|
var gap := BRIDGE_GAP / 2.0 - _get_radius()
|
|
_set_sprite_rotation(_rotation_for(normal))
|
|
_settle_onto_surface(normal, gap, delta)
|
|
velocity = Vector2.ZERO
|
|
# Holding towards the surface we're now on isn't holding away from it, so
|
|
# there's nothing to ignore until release.
|
|
ignoreWallUnstickUntilRelease = false
|
|
ignoreCeilingUnstickUntilRelease = false
|
|
_show_pose(&"Idle", REST_FRAME)
|
|
|
|
|
|
# Jumps straight to an animation state, showing its frame now rather than when
|
|
# the AnimationTree next updates. Our body jumped too: don't smooth it.
|
|
func _show_pose(state: StringName, frame: int) -> void:
|
|
reset_physics_interpolation()
|
|
sprite.frame = frame
|
|
_align_press_wall_sprite()
|
|
_update_animation_conditions(Vector2.ZERO)
|
|
var playback: AnimationNodeStateMachinePlayback = animationTree.get("parameters/playback")
|
|
playback.start(state)
|
|
|
|
|
|
# ---- 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(moveInput: Vector2) -> bool:
|
|
var normal := _get_surface_normal()
|
|
if normal == Vector2.ZERO:
|
|
return false
|
|
|
|
var inputDirection := Vector2(moveInput.x, -moveInput.y) # 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, EDGE_SENSOR_RANGE + 2)
|
|
if corner == null:
|
|
return false
|
|
|
|
# Off the surface we're on, onto the side of the platform past the edge.
|
|
return _begin_wrap(corner, normal, direction)
|
|
|
|
|
|
# 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, and a tube's mouth is too narrow to count.
|
|
if not _is_point_free(corner + direction * 2 - normal * 2):
|
|
return null
|
|
if not _is_point_free(corner + direction * radius - normal * 2):
|
|
return null
|
|
return corner
|
|
|
|
|
|
# Stops us with our leading sensor at an edge, until we've held towards it for EDGE_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)
|
|
var distanceThisFrame := absf(speedAlongSurface) * delta
|
|
var corner = _find_edge_corner(normal, direction, EDGE_STOP_DISTANCE + distanceThisFrame + 1)
|
|
var distanceToStop := INF
|
|
if corner != null:
|
|
distanceToStop = (corner - global_position).dot(direction) - EDGE_STOP_DISTANCE
|
|
if distanceToStop > distanceThisFrame:
|
|
timeSpentHoldingEdge = 0.0
|
|
return
|
|
|
|
if timeSpentHoldingEdge >= EDGE_HOLD_TIME:
|
|
return
|
|
timeSpentHoldingEdge += delta
|
|
|
|
# Set our speed along the surface to stop exactly on the spot.
|
|
var speedToReachStop := maxf(distanceToStop, 0.0) / delta
|
|
velocity += direction * (speedToReachStop - 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)
|
|
# We're already part way around the corner, so start the arc from where we are.
|
|
var arcStartAngle := (currentPosition - corner).angle()
|
|
return _begin_wrap(corner, Vector2(wallNormal, 0), Vector2.UP, arcStartAngle)
|
|
|
|
|
|
# ---- Edge wrap ----
|
|
|
|
# Swings around `corner`, from the surface facing fromNormal onto the one facing
|
|
# ontoNormal. First moves straight to the start of the arc (at arcStartAngle
|
|
# around the corner, or straight out from the surface we're leaving if not
|
|
# given). Returns false if there's no room at the end.
|
|
func _begin_wrap(corner: Vector2, fromNormal: Vector2, ontoNormal: Vector2, arcStartAngle := NAN) -> bool:
|
|
# Round to exact directions, e.g. (1, 0.0000001) to (1, 0).
|
|
fromNormal = fromNormal.round()
|
|
ontoNormal = ontoNormal.round()
|
|
|
|
var endPosition := corner + ontoNormal * _wrap_radius() - fromNormal * _get_radius()
|
|
if not _is_spot_free(endPosition):
|
|
return false
|
|
|
|
wrapCorner = corner
|
|
wrapFromNormal = fromNormal
|
|
wrapOntoNormal = ontoNormal
|
|
wrapEntryStart = global_position
|
|
if is_nan(arcStartAngle): # NAN ("not a number") means it wasn't given.
|
|
arcStartAngle = fromNormal.angle()
|
|
wrapArcStartAngle = arcStartAngle
|
|
|
|
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 entryLength := _wrap_entry_length()
|
|
var arcLength := _wrap_arc_length()
|
|
var exitOffset := _wrap_exit_offset()
|
|
var totalLength := entryLength + arcLength + exitOffset.length()
|
|
wrapDistanceTravelled = minf(wrapDistanceTravelled + wrapSpeed * delta, totalLength)
|
|
|
|
# Entry.
|
|
var distance := wrapDistanceTravelled
|
|
if distance < entryLength:
|
|
global_position = wrapEntryStart.lerp(_wrap_arc_start(), distance / entryLength)
|
|
return
|
|
distance -= entryLength
|
|
|
|
# Arc. Progress goes from 0 to 1.
|
|
var arcProgress := 1.0
|
|
if arcLength > 0.0:
|
|
arcProgress = minf(distance / arcLength, 1.0)
|
|
var angle := lerp_angle(wrapArcStartAngle, wrapOntoNormal.angle(), arcProgress)
|
|
var positionOnArc := wrapCorner + Vector2.from_angle(angle) * _wrap_radius()
|
|
_set_sprite_rotation(lerp_angle(_rotation_for(wrapFromNormal), _rotation_for(wrapOntoNormal), arcProgress))
|
|
|
|
# Exit.
|
|
var exitProgress := maxf(distance - arcLength, 0.0) / exitOffset.length()
|
|
global_position = positionOnArc + exitOffset * exitProgress
|
|
|
|
if wrapDistanceTravelled >= totalLength:
|
|
_finish_wrap(delta)
|
|
|
|
|
|
# ---- Wrap path, worked out from the wrap... variables ----
|
|
|
|
# How far from the corner the arc keeps us.
|
|
func _wrap_radius() -> float:
|
|
return _get_radius() + WRAP_MARGIN
|
|
|
|
func _wrap_arc_start() -> Vector2:
|
|
return wrapCorner + Vector2.from_angle(wrapArcStartAngle) * _wrap_radius()
|
|
|
|
func _wrap_entry_length() -> float:
|
|
return wrapEntryStart.distance_to(_wrap_arc_start())
|
|
|
|
# The arc ends pointing straight out of the new surface. Arc length = angle x radius.
|
|
func _wrap_arc_length() -> float:
|
|
return absf(angle_difference(wrapArcStartAngle, wrapOntoNormal.angle())) * _wrap_radius()
|
|
|
|
# After the arc, carry on along the new surface (away from the one we left) so
|
|
# our side ends up flat against it.
|
|
func _wrap_exit_offset() -> Vector2:
|
|
return -wrapFromNormal * _get_radius()
|
|
|
|
# The sprite rotation for standing on a surface with this normal, kept between -PI and PI.
|
|
func _rotation_for(normal: Vector2) -> float:
|
|
return wrapf(normal.angle() + PI / 2, -PI, PI)
|
|
|
|
|
|
func _finish_wrap(delta: float) -> void:
|
|
_settle_onto_surface(wrapOntoNormal, WRAP_MARGIN, delta)
|
|
# Keep our speed along the new surface so leaving the wrap isn't a sudden stop.
|
|
velocity = -wrapFromNormal * wrapSpeed
|
|
isWrapping = false
|
|
|
|
|
|
# After being moved somewhere directly (a wrap or a tube), close the `gap` to the
|
|
# surface facing `normal` and stick to it.
|
|
func _settle_onto_surface(normal: Vector2, gap: float, delta: float) -> void:
|
|
# Close the gap with move_and_slide() so is_on_floor()/is_on_wall() describe
|
|
# where we are now, not where we were before.
|
|
velocity = -normal * (gap + 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 := normal == 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
|
|
|
|
isStickingToCeiling = normal.y > 0.5
|
|
isStickingToWall = absf(normal.x) > 0.5
|
|
if isStickingToWall:
|
|
wallNormalX = normal.x
|
|
ignoreWallUnstickUntilRelease = true
|
|
ignoreCeilingUnstickUntilRelease = isStickingToCeiling
|
|
|
|
|
|
# ---- Tubes ----
|
|
|
|
# Holding into the mouth of a tube (while stuck to a surface) for
|
|
# TUBE_ENTER_HOLD_TIME squeezes us through it, if it leads somewhere we fit.
|
|
# Meanwhile we hold still against the mouth. True while squeezing or once we're in.
|
|
func _update_tube_squeeze(delta: float, moveInput: Vector2) -> bool:
|
|
var tube := {}
|
|
if tubeReentryCooldown <= 0.0 and _get_surface_normal() != Vector2.ZERO:
|
|
tube = _find_tube(moveInput, velocity * delta)
|
|
isSqueezingIntoTube = not tube.is_empty()
|
|
tubeSqueezeDirection = tube.direction if isSqueezingIntoTube else Vector2.ZERO
|
|
if not isSqueezingIntoTube:
|
|
timeSpentSqueezingIntoTube = 0.0
|
|
return false
|
|
|
|
timeSpentSqueezingIntoTube += delta
|
|
if timeSpentSqueezingIntoTube >= TUBE_ENTER_HOLD_TIME:
|
|
timeSpentSqueezingIntoTube = 0.0
|
|
isSqueezingIntoTube = false
|
|
_enter_tube(tube)
|
|
return true
|
|
|
|
# The mouth counts from a little way off (see _find_tube_towards), so close
|
|
# any gap: hold still pressed right up against it, wherever we were when we
|
|
# arrived. move_and_collide() leaves is_on_floor() and friends alone, so
|
|
# climbing down a wall to a mouth in the floor leaves us on the wall.
|
|
move_and_collide(tube.direction * (TUBE_ENTRY_REACH + maxf(velocity.dot(tube.direction) * delta, 0.0)))
|
|
velocity = Vector2.ZERO
|
|
_update_facing(moveInput)
|
|
_update_animation_conditions(moveInput)
|
|
_update_sprite_rotation(delta)
|
|
return true
|
|
|
|
|
|
# The tube whose mouth we're pressing straight into, if we can go in: {layer,
|
|
# cell, direction (into the tube)}, plus .path through it for an ordinary tube.
|
|
# Empty if there isn't one. Only straight in: on the floor beside a wall with a
|
|
# mouth in it, up and towards the wall climbs the wall.
|
|
# Ordinary tubes must lead somewhere we fit. Manual ones needn't: we can always
|
|
# back out.
|
|
# `step`: how far we're about to move. Mouths that far ahead count too, so we
|
|
# can't step straight past one: climbing down a wall onto the floor beside a
|
|
# mouth in it, say, instead of squeezing in from the wall.
|
|
func _find_tube(moveInput: Vector2, step := Vector2.ZERO) -> Dictionary:
|
|
if moveInput == Vector2.ZERO:
|
|
return {}
|
|
var inputDirection := Vector2(moveInput.x, -moveInput.y).normalized() # Up is negative y.
|
|
for direction: Vector2 in [Vector2.UP, Vector2.RIGHT, Vector2.DOWN, Vector2.LEFT]:
|
|
if inputDirection.dot(direction) < TUBE_ENTER_MIN_ALIGNMENT:
|
|
continue
|
|
return _find_tube_towards(direction, maxf(step.dot(direction), 0.0))
|
|
return {}
|
|
|
|
|
|
func _find_tube_towards(direction: Vector2, extraReach := 0.0) -> Dictionary:
|
|
var radius := _get_radius()
|
|
var across := direction.orthogonal()
|
|
var reach := radius + TUBE_ENTRY_REACH + extraReach
|
|
for layer in _get_tube_layers():
|
|
# Check the tile ahead of our middle and of each side, in case we're
|
|
# between two rows of tiles.
|
|
for side: float in [0.0, -radius, radius]:
|
|
var probe := global_position + direction * reach + across * side
|
|
var cell := layer.local_to_map(layer.to_local(probe))
|
|
if _get_tube_openings(layer, cell) & _tube_side_bit(-direction) == 0:
|
|
continue
|
|
if not OneWayTube.can_enter(layer, cell, Vector2i(direction)):
|
|
continue # The exit end of a one-way tube.
|
|
# The mouth must be within our width, and touching (or nearly) our side.
|
|
var toMouth := _tube_cell_point(layer, cell, -direction) - global_position
|
|
if absf(toMouth.dot(across)) > radius or toMouth.dot(direction) > reach:
|
|
continue
|
|
var tube := {layer = layer, cell = cell, direction = direction}
|
|
if TubeSteer.is_manual(layer, cell):
|
|
return tube
|
|
var path := PixelStream.trace_tube(layer, cell, Vector2i(direction))
|
|
if not path.is_empty() and not _tube_exit_pose_for(path).is_empty():
|
|
tube.path = path
|
|
return tube
|
|
return {}
|
|
|
|
|
|
# Where we come out of the ordinary tube along `path` (see _tube_exit_pose).
|
|
func _tube_exit_pose_for(path: PackedVector2Array) -> Dictionary:
|
|
var exitMouth := path[path.size() - 1]
|
|
var exitDirection := (exitMouth - path[path.size() - 2]).normalized().round()
|
|
return _tube_exit_pose(exitMouth, exitDirection)
|
|
|
|
|
|
# How we come out of a tube mouth facing `outward`: .spriteTransform (where the
|
|
# sprite reforms), .normal (the surface we'll be stuck to) and .appearAt (where
|
|
# we reappear, a pixel off it). Empty if there's no room for us.
|
|
func _tube_exit_pose(mouth: Vector2, outward: Vector2) -> Dictionary:
|
|
var radius := _get_radius()
|
|
|
|
# Come out stuck to the face the tube opens from, like after a wrap. Even
|
|
# with a floor right below a sideways mouth, we stick to the wall.
|
|
var exitNormal := outward
|
|
var exitPosition := mouth + outward * radius
|
|
|
|
# We reappear a pixel off the surface and settle onto it (see _exit_tube).
|
|
var appearAt := exitPosition + exitNormal
|
|
if not _is_spot_free(appearAt):
|
|
return {}
|
|
return {spriteTransform = Transform2D(_rotation_for(exitNormal), exitPosition.round()),
|
|
normal = exitNormal, appearAt = appearAt}
|
|
|
|
|
|
# Turns us into pixels in the tube _find_tube gave us.
|
|
func _enter_tube(tube: Dictionary) -> void:
|
|
# Items don't fit through tubes: leave it at the mouth.
|
|
if carriedItem != null:
|
|
carriedItem.drop()
|
|
carriedItem = null
|
|
|
|
if tube.has("path"):
|
|
tubeExitPose = _tube_exit_pose_for(tube.path)
|
|
tubePixels = PixelStream.new()
|
|
get_parent().add_child(tubePixels)
|
|
tubePixels.start(sprite, tube.path, TUBE_WIDTH, TUBE_MAX_FLOW_LENGTH, tubeExitPose.spriteTransform, REST_FRAME)
|
|
else:
|
|
# Backing out of the mouth we went in by reforms us right here.
|
|
var spriteTransform := sprite.get_global_transform()
|
|
spriteTransform.origin = spriteTransform.origin.round() # Snapped like the renderer does.
|
|
var entryPose := {spriteTransform = spriteTransform, normal = _get_surface_normal(),
|
|
appearAt = global_position}
|
|
# Except into a mouth in a wall from the floor or ceiling: we come back out
|
|
# onto the wall, like out of any other mouth, not on the floor or ceiling.
|
|
if tube.direction.x != 0.0 and _get_surface_normal().x == 0.0:
|
|
var mouth := _tube_cell_point(tube.layer, tube.cell, -tube.direction)
|
|
var wallPose := _tube_exit_pose(mouth, -tube.direction)
|
|
if not wallPose.is_empty():
|
|
wallPose.startTransform = spriteTransform # The goo still starts as we look now.
|
|
entryPose = wallPose
|
|
tubeSteer = TubeSteer.new()
|
|
tubeSteer.indicatorColor = tubeIndicatorColor
|
|
tubeSteer.indicatorBorderColor = tubeIndicatorBorderColor
|
|
tubeSteer.indicatorRadius = tubeIndicatorRadius
|
|
get_parent().add_child(tubeSteer)
|
|
tubeSteer.start(sprite, tube.layer, tube.cell, Vector2i(tube.direction), TUBE_WIDTH, TUBE_MAX_FLOW_LENGTH,
|
|
entryPose, _tube_exit_pose, REST_FRAME)
|
|
|
|
isInTube = true
|
|
velocity = Vector2.ZERO
|
|
isStickingToWall = false
|
|
isStickingToCeiling = false
|
|
isHoppingAcross = false
|
|
timeSpentHoldingEdge = 0.0
|
|
timeSpentHoldingUpOnFloor = 0.0
|
|
timeSpentUnstickingWall = 0.0
|
|
timeSpentUnstickingCeiling = 0.0
|
|
hide()
|
|
collisionShape.set_deferred("disabled", true)
|
|
wrapSound.play()
|
|
|
|
|
|
func _update_tube(delta: float, moveInput: Vector2) -> void:
|
|
if tubeSteer != null:
|
|
tubeSteer.steer(Vector2(moveInput.x, -moveInput.y), delta) # Up is negative y.
|
|
if tubeSteer.isFinished:
|
|
var pose: Dictionary = tubeSteer.exitPose
|
|
tubeSteer.queue_free()
|
|
tubeSteer = null
|
|
_exit_tube(pose, delta)
|
|
elif tubePixels.isFinished:
|
|
tubePixels.queue_free()
|
|
tubePixels = null
|
|
_exit_tube(tubeExitPose, delta)
|
|
|
|
|
|
# The point the camera should keep on screen (see RoomCamera). In a tube we're
|
|
# hidden at the entrance, so it's the front of our goo instead.
|
|
func get_camera_focus() -> Vector2:
|
|
if isInTube:
|
|
if tubeSteer != null:
|
|
return tubeSteer.get_focus()
|
|
if tubePixels != null:
|
|
return tubePixels.get_focus()
|
|
return global_position
|
|
|
|
|
|
# Air rushing into a one-way tube's entrance (TubeAirCurrents) pulls us into
|
|
# the tube at `cell` heading `direction`, without pressing anything, if it
|
|
# leads somewhere we fit.
|
|
func pull_into_tube(layer: TileMapLayer, cell: Vector2i, direction: Vector2) -> void:
|
|
if isInTube or isWrapping or isBridging or tubeReentryCooldown > 0.0:
|
|
return
|
|
var path := PixelStream.trace_tube(layer, cell, Vector2i(direction))
|
|
if path.is_empty() or _tube_exit_pose_for(path).is_empty():
|
|
return
|
|
_enter_tube({layer = layer, cell = cell, direction = direction, path = path})
|
|
|
|
|
|
# Air blowing out of a one-way tube's exit (TubeAirCurrents) knocks us off whatever
|
|
# we're stuck to and pushes us at `push` (px/s, at least: we keep any speed we
|
|
# already have that way). Called every physics frame we're in the air stream.
|
|
func blow_away(push: Vector2) -> void:
|
|
if isInTube or isWrapping or isBridging:
|
|
return
|
|
isStickingToWall = false
|
|
isStickingToCeiling = false
|
|
isHoppingAcross = false
|
|
timeSpentUnstickingWall = 0.0
|
|
timeSpentUnstickingCeiling = 0.0
|
|
timeSpentHoldingEdge = 0.0
|
|
timeSpentHoldingUpOnFloor = 0.0
|
|
timeSpentSqueezingIntoTube = 0.0
|
|
if push.x != 0.0 and velocity.x * signf(push.x) < absf(push.x):
|
|
velocity.x = push.x
|
|
if push.y != 0.0 and velocity.y * signf(push.y) < absf(push.y):
|
|
velocity.y = push.y
|
|
|
|
|
|
func _exit_tube(pose: Dictionary, delta: float) -> void:
|
|
isInTube = false
|
|
tubeReentryCooldown = TUBE_REENTRY_DELAY
|
|
|
|
# Visible again before anything below, as Godot ignores
|
|
# reset_physics_interpolation() on hidden nodes.
|
|
show()
|
|
var normal: Vector2 = pose.normal
|
|
global_position = pose.appearAt
|
|
collisionShape.disabled = false
|
|
_set_sprite_rotation(_rotation_for(normal))
|
|
_settle_onto_surface(normal, 1.0, delta)
|
|
velocity = Vector2.ZERO
|
|
# A jump, not movement: don't smooth from where we went in. Without this the
|
|
# sprite flashes up at the entrance for a frame.
|
|
reset_physics_interpolation()
|
|
# Show the frame our pixels just made, and let the AnimationTree carry on from
|
|
# there. Without start() it would still be in whatever state we went in with.
|
|
sprite.frame = REST_FRAME
|
|
_align_press_wall_sprite() # Un-shift now, in case we went in pressing a wall.
|
|
_update_animation_conditions(Vector2.ZERO)
|
|
var playback: AnimationNodeStateMachinePlayback = animationTree.get("parameters/playback")
|
|
playback.start(&"Idle")
|
|
wrapSound.play()
|
|
|
|
|
|
func _get_tube_layers() -> Array[TileMapLayer]:
|
|
if hasFoundTubeLayers:
|
|
return tubeLayers
|
|
hasFoundTubeLayers = true
|
|
for node in get_tree().root.find_children("*", "TileMapLayer", true, false):
|
|
var layer := node as TileMapLayer
|
|
if layer.tile_set and layer.tile_set.get_custom_data_layer_by_name(TUBE_DATA_LAYER) != -1:
|
|
tubeLayers.append(layer)
|
|
return tubeLayers
|
|
|
|
|
|
# Which sides of the tile at `cell` are open (TUBE_OPEN_... bits). 0 if it isn't a tube.
|
|
func _get_tube_openings(layer: TileMapLayer, cell: Vector2i) -> int:
|
|
var data := layer.get_cell_tile_data(cell)
|
|
if data == null:
|
|
return 0
|
|
return data.get_custom_data(TUBE_DATA_LAYER)
|
|
|
|
|
|
func _tube_side_bit(direction: Vector2) -> int:
|
|
if direction == Vector2.UP: return TUBE_OPEN_UP
|
|
if direction == Vector2.RIGHT: return TUBE_OPEN_RIGHT
|
|
if direction == Vector2.DOWN: return TUBE_OPEN_DOWN
|
|
if direction == Vector2.LEFT: return TUBE_OPEN_LEFT
|
|
return 0
|
|
|
|
|
|
# The global middle of `cell`'s side facing `side`, or its centre for Vector2.ZERO.
|
|
func _tube_cell_point(layer: TileMapLayer, cell: Vector2i, side: Vector2) -> Vector2:
|
|
var halfTile := Vector2(layer.tile_set.tile_size) / 2.0
|
|
return layer.to_global(layer.map_to_local(cell) + side * halfTile)
|
|
|
|
# ---- Items ----
|
|
|
|
# A CarryItem we touched asks to be carried. Returns whether we took it.
|
|
func pick_up_item(item: CarryItem) -> bool:
|
|
if carriedItem != null or isInTube:
|
|
return false
|
|
# Just out of a tube, physics still has our shape back where we went in for a
|
|
# frame, so it can report us touching an item we left there. Check it's really
|
|
# within reach of where we are.
|
|
var reach := _get_radius() + item.PICKUP_SIZE.length() / 2.0
|
|
if global_position.distance_to(item.global_position) > reach:
|
|
return false
|
|
carriedItem = item
|
|
item.attach_to(self)
|
|
return true
|
|
|
|
# ---- 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()
|