SpriteBase - alexneargarder/Broforce-Docs GitHub Wiki
SpriteBase
Table of Contents
- Unity Lifecycle & Setup
- Animation & Sprite Systems
- Mesh Management
- UV Coordinate System
- Sprite Configuration
- Helper & Utility
Unity Lifecycle & Setup
Methods
public virtual void Awake()
Unity Awake method that initializes the sprite's mesh components and texture. Gets MeshFilter and MeshRenderer components, destroys any existing shared mesh, extracts texture from material, starts the animation pump if needed, and creates normals array if requested.
public virtual void Clear()
Resets the sprite to default state. Disables billboarding, sets color to white, resets offset to zero, and clears the animation complete delegate.
public virtual void Init()
Initializes the sprite mesh with vertices, UVs, colors, and triangles. Creates a new dynamic mesh if needed, sets up winding order, calculates UVs with bleed compensation, configures pixel-perfect rendering if enabled, and applies initial size and color.
public void OnDisable()
Unity OnDisable callback that temporarily removes the sprite from the animation system when disabled. Preserves the animating state so it can be restored when re-enabled.
public void OnEnable()
Unity OnEnable callback that re-adds the sprite to the animation system if it was animating when disabled. Only operates in play mode to avoid editor issues.
protected virtual void Start()
Unity Start method that completes sprite initialization. Stores the initial UV rectangle, calculates pixels per UV unit from texture dimensions, and sets up the camera reference for pixel-perfect rendering calculations.
Animation & Sprite Systems
Methods
protected void AddToAnimatedList()
Adds this sprite to the global animation pump for frame updates. Starts the animation pump if not already running and marks the sprite as animating.
public virtual void Copy(SpriteBase s)
Copies configuration from another sprite including material, texture, plane orientation, winding order, offset, anchor method, resize settings, pixel perfect flag, and color. Updates texture dimensions for UV calculations.
Parameters:
- SpriteBase s: Source sprite to copy settings from
public bool IsAnimating()
Checks whether this sprite is currently animating.
Returns:
bool
: True if the sprite is in the animation update list, false otherwise.
public void PauseAnim()
Pauses the sprite animation by removing it from the animation update list. The animation state is preserved and can be resumed later.
public virtual void RecalcTexture()
Refreshes texture reference from the current material's main texture. Updates pixel dimensions used for UV coordinate calculations. Called when material or texture changes.
protected void RemoveFromAnimatedList()
Removes this sprite from the global animation pump, stopping frame updates. Marks the sprite as no longer animating.
public void RevertToStatic()
Reverts the sprite to its static (non-animated) state. Stops any active animation, recalculates UVs, applies bleed compensation, and optionally resizes based on pixel-perfect or auto-resize settings.
public void SetAnimCompleteDelegate(SpriteBase.AnimCompleteDelegate del)
Sets a delegate to be called when the current animation completes. Used for triggering events or transitioning to other animations when an animation cycle finishes.
Parameters:
- AnimCompleteDelegate del: Delegate to invoke when animation completes, or null to clear
public void SetColor(Color c)
Sets the vertex color for all four vertices of the sprite. Color is multiplied with texture in the shader for tinting effects.
Parameters:
- Color c: Color to apply to all vertices
public void SetSpriteResizedDelegate(SpriteBase.SpriteResizedDelegate del)
Sets a delegate to be called whenever the sprite is resized. Useful for updating dependent systems when sprite dimensions change due to UV updates or manual resizing.
Parameters:
- SpriteResizedDelegate del: Delegate to invoke when sprite is resized, receives new width, height, and sprite reference
public virtual bool StepAnim(float time)
Virtual method for advancing sprite animation by the specified time delta. Base implementation returns false. Derived classes override this to implement actual animation logic.
Parameters:
- float time: Time elapsed since last animation step in seconds
Returns:
bool
: Always returns false in base implementation. Derived classes return true if animation continues, false if complete
public virtual void StopAnim()
Virtual method that stops the sprite animation. Base implementation is empty - override in derived classes to implement custom animation stopping behavior.
public void TransformBillboarded(Transform t)
Transforms the sprite to face a specific transform (billboard effect). Currently empty in base class, likely implemented in derived classes for camera-facing sprites.
Parameters:
- Transform t: Transform to face towards
Properties
public MeshRenderer MeshRenderer { get; set; }
Gets or sets the MeshRenderer component used to render this sprite. Provides direct access to rendering properties like materials and shadows.
Fields
protected bool animating
Indicates whether the sprite is currently playing an animation. When true, the sprite is registered with the SpriteAnimationPump for regular StepAnim updates. Managed by AddToAnimatedList/RemoveFromAnimatedList methods and preserved across OnDisable/OnEnable cycles.
protected SpriteBase.AnimCompleteDelegate animCompleteDelegate
Delegate invoked when an animation completes playback. Set via SetAnimCompleteDelegate method and called by derived classes (PackedSprite, SpriteSM) when they finish playing an animation sequence. Allows external code to respond to animation completion events for state transitions or chaining animations.
public int defaultAnim
The index of the animation to play by default. Used in conjunction with playAnimOnStart to automatically begin animation playback when the sprite initializes. Also used as the fallback animation when an animation completes with the Play_Default_Anim end action. Must be a valid index within the animations array.
protected int framesToAdvance
The number of animation frames to advance in the current update, calculated as timeSinceLastFrame / timeBetweenAnimFrames. Allows animations to catch up if multiple frames worth of time have elapsed since the last update, ensuring smooth playback even with variable frame rates.
public bool playAnimOnStart
When true, automatically plays the default animation when the sprite starts. Used by derived classes like PackedSprite and SpriteSM to trigger initial animation playback during their Start method if a valid defaultAnim index is specified and the application is playing.
protected SpriteBase.SpriteResizedDelegate resizedDelegate
Delegate invoked when the sprite is resized via SetSize method. Receives the new width, height, and a reference to the sprite being resized. Allows external code to respond to size changes for layout updates or dependent object adjustments. Set via SetSpriteResizedDelegate method.
protected float timeBetweenAnimFrames
The duration in seconds between animation frames, calculated as 1/framerate. Used with timeSinceLastFrame to determine when to advance the animation. Set by derived classes when playing animations to control playback speed.
protected float timeSinceLastFrame
Accumulates elapsed time since the last animation frame change. Used by derived animation classes to determine when to advance to the next frame based on the animation framerate. Reset to zero (minus overflow) each time a frame advances.
Mesh Management
Methods
public void CalcEdges()
Calculates the top-left and bottom-right corner positions based on the current anchor method. Supports nine anchor points (corners, edges, and center) for flexible sprite positioning.
public void CalcSize()
Calculates sprite dimensions based on rendering mode. In pixel-perfect mode, calculates size from screen pixels and orthographic camera size. In auto-resize mode, scales proportionally with UV changes. Updates sprite size after calculation.
public void RefreshVertices()
Recalculates and updates all vertex positions with shear and skew effects applied. Used for creating slanted or distorted sprites while maintaining proper UV mapping.
public void SetSize(float width, float height)
Sets the sprite size and updates vertex positions based on the current plane orientation. Routes to appropriate size setting method (SetSizeXY, SetSizeXZ, or SetSizeYZ) and invokes resize delegate if set.
Parameters:
- float width: New width of the sprite in world units
- float height: New height of the sprite in world units
protected void SetSizeXY(float w, float h)
Updates sprite vertices for XY plane orientation (standard 2D sprite facing camera). Calculates edge positions based on anchor point and updates all four vertices with proper offset application.
Parameters:
- float w: Width of the sprite in world units
- float h: Height of the sprite in world units
protected void SetSizeXZ(float w, float h)
Updates sprite vertices for XZ plane orientation (ground/ceiling sprite). Positions vertices in the horizontal plane with Y as the up axis.
Parameters:
- float w: Width of the sprite in world units
- float h: Height (depth) of the sprite in world units
protected void SetSizeYZ(float w, float h)
Updates sprite vertices for YZ plane orientation (wall sprite facing sideways). Positions vertices in the YZ plane with X as the normal direction.
Parameters:
- float w: Width of the sprite in world units
- float h: Height of the sprite in world units
Fields
protected Color[] colors = new Color[4]
Array of 4 vertex colors for the sprite quad. All elements set to same color value by SetColor(). Allows per-vertex tinting if needed. Applied to mesh.colors for rendering.
protected int[] faces = new int[6]
Triangle indices array defining two triangles (6 indices) that form the sprite quad. Order determined by SetWindingOrder() - CCW uses [0,1,3,3,1,2] and CW uses [0,3,1,3,2,1].
protected Mesh mesh
The dynamically created Mesh object for this sprite. Created in Init() with MarkDynamic() for frequent updates. Stores vertices, UVs, colors, and triangle data for rendering the sprite quad.
protected MeshFilter meshFilter
Reference to the MeshFilter component attached to this GameObject. Initialized in Awake() and used to assign the dynamically created mesh. Required component for sprite rendering.
protected MeshRenderer meshRenderer
Reference to the MeshRenderer component attached to this GameObject. Initialized in Awake() and exposed via MeshRenderer property. Used to access material and texture information.
protected Vector3[] normals
Optional array of vertex normals for lighting calculations. Only created when createNormals is true. All normals face backward (Vector3.back) for typical 2D sprite lighting.
protected Texture texture
Reference to the main texture used by this sprite. Retrieved from material's _MainTex property in Awake() and RecalcTexture(). Used for pixel-to-UV calculations and dimension calculations.
protected Vector2[] uvs = new Vector2[4]
Primary UV coordinates array for the 4 sprite vertices. Updated by UpdateUVs() based on uvRect and winding order. Defines which part of the texture maps to each vertex.
protected Vector2[] uvs2 = new Vector2[4]
Secondary UV coordinates array for special effects. Set by SetUV2() to standard 0-1 quad values regardless of primary UVs. Can be used by shaders for effects independent of texture mapping.
protected Vector3[] vertices = new Vector3[4]
Array of 4 vertices defining the sprite quad corners. Updated by SetSizeXY/XZ/YZ and RefreshVertices() methods. Order depends on winding setting. Applied to mesh for rendering.
UV Coordinate System
Methods
public virtual void CalcUVs()
Virtual method for calculating UV coordinates. Base implementation is empty. Derived classes override this to implement specific UV calculation logic for different sprite types.
public Vector2 PixelCoordToUVCoord(int x, int y)
Converts pixel coordinates to UV coordinates with Y-axis flipping for Unity's UV system. Unity UVs have origin at bottom-left while textures have origin at top-left.
Parameters:
- Vector2 xy: Pixel coordinates to convert.
Returns:
Vector2
: UV coordinates with flipped Y axis.
public Vector2 PixelCoordToUVCoord(int x, int y)
Converts integer pixel coordinates to UV coordinates with Y-axis flipping for Unity's UV system.
Parameters:
- int x: X pixel coordinate.
- int y: Y pixel coordinate.
Returns:
Vector2
: UV coordinates with flipped Y axis.
public Vector2 PixelSpaceToUVSpace(int x, int y)
Converts pixel coordinates to UV space (0-1 range) based on texture dimensions.
Parameters:
- Vector2 xy: Pixel coordinates to convert.
Returns:
Vector2
: UV coordinates in 0-1 range, or Vector2.zero if no texture is assigned.
public Vector2 PixelSpaceToUVSpace(int x, int y)
Converts integer pixel coordinates to UV space (0-1 range) based on texture dimensions.
Parameters:
- int x: X pixel coordinate.
- int y: Y pixel coordinate.
Returns:
Vector2
: UV coordinates in 0-1 range.
public void SetBleedCompensation(Vector2 xy)
Applies the current bleed compensation values to adjust UV coordinates. Bleed compensation prevents texture bleeding by inset the UV rectangle.
public void SetBleedCompensation(Vector2 xy)
Sets and applies bleed compensation with specified pixel values. Bleed compensation prevents texture bleeding at sprite edges.
Parameters:
- float x: Horizontal bleed compensation in pixels.
- float y: Vertical bleed compensation in pixels.
public void SetBleedCompensation(Vector2 xy)
Sets and applies bleed compensation from a Vector2. Converts pixel values to UV space and insets the UV rectangle to prevent texture bleeding.
Parameters:
- Vector2 xy: Bleed compensation values in pixels (x and y).
public void SetUV2()
Sets secondary UV coordinates (UV2) for shader effects. Always uses normalized 0-1 coordinates regardless of primary UV settings, useful for effects that need full texture coverage.
public void SetUVs(Rect uv)
Sets the UV rectangle for texture mapping. Applies bleed compensation and optionally recalculates size for pixel-perfect or auto-resize sprites.
Parameters:
- Rect uv: The UV coordinate rectangle (0-1 range).
public void SetUVsFromPixelCoords(Rect pxCoords)
Sets UV coordinates from pixel coordinates on the texture. Converts pixel coordinates to UV space (0-1 range) and applies settings.
Parameters:
- Rect pxCoords: Rectangle defining the sprite area in texture pixels.
public void UpdateUVs()
Updates the UV coordinates of all four vertices based on current UV rectangle and winding order. Handles both clockwise and counter-clockwise winding to ensure proper texture display.
Fields
protected Vector2 bleedCompensationUV
UV space inset calculated from bleedCompensation pixel values. Used internally by SetBleedCompensation() to adjust uvRect boundaries, preventing texture bleeding by moving UV coordinates inward from texture edges.
protected Vector2 bottomRight
Calculated bottom-right corner position of sprite in local space. Set by CalcEdges() based on sprite dimensions and anchor method. Used as reference point for vertex calculations in SetSize methods.
protected Vector2 pixelsPerUV
Stores the texture dimensions as pixels per UV unit. The x component contains the texture width in pixels and the y component contains the texture height. This value is automatically updated whenever the texture changes and is used to convert between pixel coordinates and UV coordinates during sprite rendering calculations.
protected Rect prevUVRect
Previous frame's UV rectangle used for auto-resize calculations. When autoResize is enabled, CalcSize() compares current uvRect to this value to proportionally scale sprite dimensions when UV region changes.
protected Vector2 topLeft
Calculated top-left corner position of sprite in local space. Set by CalcEdges() based on sprite dimensions and anchor method. Used as reference point for vertex calculations in SetSize methods.
protected Rect uvRect
Rectangle defining the texture coordinates for this sprite in UV space (0-1 range). Modified by SetUVs(), SetUVsFromPixelCoords(), and SetBleedCompensation(). Used by UpdateUVs() to set mesh UV coordinates.
Sprite Configuration
Methods
public void SetAnchor(SpriteBase.ANCHOR_METHOD a)
Sets the anchor point for sprite positioning. Determines which part of the sprite aligns with its transform position.
Parameters:
- ANCHOR_METHOD a: The anchor method defining the alignment point.
public void SetCamera(Camera c)
Sets the camera reference for pixel-perfect calculations. Updates screen size from camera's pixel dimensions and recalculates sprite size to maintain pixel-perfect appearance.
Parameters:
- Camera c: Camera to use for pixel-perfect calculations, returns immediately if null
public void SetOffset(Vector3 o)
Sets an additional position offset applied to the sprite vertices. Useful for fine-tuning sprite positioning.
Parameters:
- Vector3 o: The 3D offset to apply to sprite vertices.
public void SetPlane(SpriteBase.SPRITE_PLANE p)
Sets the orientation plane for the sprite mesh (XY, XZ, or YZ). Rebuilds the mesh vertices for the new plane orientation.
Parameters:
- SPRITE_PLANE p: The sprite plane orientation to use.
public void SetWindingOrder(SpriteBase.WINDING_ORDER order)
Sets the triangle winding order for the mesh faces. Clockwise (CW) renders the front face, counter-clockwise (CCW) renders the back face.
Parameters:
- WINDING_ORDER order: The winding order to apply (CW or CCW).
Fields
public SpriteBase.ANCHOR_METHOD anchor = SpriteBase.ANCHOR_METHOD.MIDDLE_CENTER
The anchor point determining sprite alignment with its transform position. Default is MIDDLE_CENTER for centered sprites.
public bool autoResize
Enables automatic sprite resizing when UV coordinates change. When true and UV rect changes, sprite dimensions are scaled proportionally to maintain the same aspect ratio as the texture region. Checked in CalcSize(), Copy(), and UV update methods.
public bool billboarded
Flag indicating if sprite should face the camera (billboard mode). Currently only set/cleared but not actively used in base implementation - likely utilized by derived classes or external systems.
public Vector2 bleedCompensation
Pixel-based inset values to prevent texture bleeding at sprite edges. Applied to UV coordinates to slightly shrink the sampled area.
public Color color = Color.white
Vertex color applied to all four sprite vertices for tinting. Defaults to white (no tint). Updated via SetColor() which applies this color to the colors array and mesh.
public bool createNormals
Controls whether mesh normals are generated. When true, creates a normals array with all vertices facing backward (Vector3.back) during Awake() and applies them during Init(). Used for sprites that need proper lighting.
protected Camera curCamera
Reference to the current camera used for pixel-perfect calculations. Set by SetCamera() method. Used to get orthographic size for converting between world units and screen pixels.
public float height
The height of the sprite in world units. Used for mesh vertex calculation and size-based operations.
public Vector3 offset = default(Vector3)
3D position offset applied to all sprite vertices. Added to calculated vertex positions in SetSizeXY/XZ/YZ methods to shift the entire sprite mesh. Can be updated via SetOffset() method.
public bool pixelPerfect
Enables pixel-perfect sprite rendering mode. When true, sprite dimensions are automatically calculated based on camera orthographic size and screen dimensions to ensure 1:1 pixel mapping. Used in Init(), CalcSize(), and throughout rendering pipeline.
public SpriteBase.SPRITE_PLANE plane
The orientation plane for the sprite mesh. Determines whether the sprite is rendered on the XY (default 2D), XZ (ground), or YZ plane.
protected static Vector2 screenSize
Static screen dimensions in pixels shared across all sprites. Updated by SetCamera() with camera's pixel width/height. Used in CalcSize() for pixel-perfect calculations with orthographic camera size.
public float shearAmount
Horizontal shear factor for skewing sprite vertices. Applied to top vertices when RefreshVertices() is called, creating a parallelogram effect by offsetting the top edge horizontally by this amount multiplied by sprite width.
public float skewAmount
Vertical skew factor for tilting sprite vertices. Applied when RefreshVertices() is called - subtracts from top-left vertex Y and adds to top-right vertex Y, creating a tilted appearance.
public float width
The width of the sprite in world units. Used for mesh vertex calculation and size-based operations.
public SpriteBase.WINDING_ORDER winding = SpriteBase.WINDING_ORDER.CW
The triangle winding order for mesh faces. CW (clockwise) shows the front face, CCW (counter-clockwise) shows the back face. Default is CW.
protected float worldUnitsPerScreenPixel
The conversion factor between world units and screen pixels for pixel-perfect rendering. Calculated as (camera orthographic size * 2) / screen height when pixelPerfect is enabled. This value ensures sprites are rendered at exact pixel boundaries without filtering artifacts, maintaining the crisp pixel art aesthetic.
Helper & Utility
Fields
protected int i
General purpose loop iterator variable. Used by derived classes as a temporary variable during various operations. Not used directly in SpriteBase but provided as a protected member for subclass convenience.
protected Vector2 tempUV
Temporary UV coordinate storage used during calculations. Used in CalcSize for auto-resize UV ratio calculations and in SetUVsFromPixelCoords for pixel-to-UV conversions. Avoids allocation of new Vector2 objects during frequent operations.