Skip to content

Instantly share code, notes, and snippets.

@paradrogue
Last active January 26, 2021 14:33
Show Gist options
  • Save paradrogue/4c88c469bc3d1cdaa607322a82d9bb23 to your computer and use it in GitHub Desktop.
Save paradrogue/4c88c469bc3d1cdaa607322a82d9bb23 to your computer and use it in GitHub Desktop.
A simple sprite stack for Godot. Can handle rotation of the parent node.
extends Node2D
# The texture (spritesheet) to use as the stacked sprite.
# This should be of the form <frames*height> x <height>.
# i.e. a 10 frame stack of 32px x 32px images should 320px x 32px.
export (Texture) var texture:Texture
# The vertical scale multiplier.
export (float) var v_scale:float = 1.0
func _ready() -> void:
# Work out how many frames there are.
# All sprites are build from the spritesheet on a lower-to-higher basis.
var frames = texture.get_width()/texture.get_height()
# Build the stack of sprites.
for frame in frames:
# Create a new sprite and add it as a child of the current node.
var layer := Sprite.new()
add_child(layer)
# Set the sprites texture to the spritesheet.
layer.texture = texture
# Set the total number of frames, and set the current frame for this
# sprite.
layer.hframes = frames
layer.frame = frame
# Place each sprite on it's own (local) z-index so that they are
# stacked properly.
layer.z_as_relative = true
layer.z_index = frame
# Set the position of the sprite upward (-Y). Scale appropriately.
layer.position.y = -(frame * v_scale)
update()
# Update the sprite stack to cater for changes in rotation.
func _process(delta: float) -> void:
var layers = get_children()
# Work out the rotational vector based on the current rotation.
var rotational_vector := -Vector2(sin(rotation), cos(rotation))
# Apply the rotational vector to each of the layers and update it's relative
# position.
for i in range(layers.size()):
# Scale appropriately.
var scale = i * v_scale
layers[i].position = rotational_vector * scale
@paradrogue
Copy link
Author

A simple crate.
crate_stack

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment