Grenade - alexneargarder/Broforce-Docs GitHub Wiki

Grenade

Table of Contents

Unity Lifecycle & Setup

Methods

protected override void Awake()

Initializes the grenade when the GameObject is created. Sets up the fragile collision layer for detecting breakable objects and initializes the bounce tracking list if needed.


protected virtual void RegisterGrenade()

Registers this grenade with the Map's tracking systems. If the grenade is marked as shootable, it's added to the shootable grenades list for AI targeting. All grenades are added to the general grenade tracking list.


public void SetToDisable(bool disabledAtStart)

Sets whether this grenade should start in a disabled state. Used for pre-placed grenades in levels that shouldn't be active immediately.

Parameters:

  • bool disabledAtStart: True to start disabled, false for normal behavior

public void SetupGrenade(int newSeed, int pNum, MonoBehaviour _FiredBy)

Initializes grenade ownership and visual properties. Sets the player number, random seed, and who fired the grenade. Configures trail renderer colors based on the player number, using player-specific colors for players 0-3 and red/yellow for others.

Parameters:

  • int newSeed: Random seed for consistent behavior
  • int pNum: Player number who owns this grenade
  • MonoBehaviour _FiredBy: The unit that launched this grenade

protected override void Start()

Completes grenade initialization after all Awake calls. Caches the main material, sets up the ground collision layer, registers the grenade with game systems, and handles special disabled spawn states for pre-placed grenades.


Fields

protected bool disabledAtStart

When true, the grenade starts in a disabled state. Used for pre-placed grenades in levels that shouldn't be active until triggered. Set via SetToDisable method.


Combat & Damage

Methods

public override void Death()

Handles the grenade explosion. Damages terrain, creates visual effects, and damages units within the blast radius. Only the local player's grenades calculate unit damage to prevent networking issues. Awards achievements for special kills and triggers explosion effects.


protected virtual void DestroyGrenade()

Removes the grenade from all tracking systems and destroys the GameObject. Called after the explosion effects have been created.


public virtual void Knock(float xDiff, float yDiff, float xI, float yI)

Applies knockback force to the grenade from explosions or other impacts. Adjusts velocity based on the impact force and grenade weight, adds rotational spin, and plays a defend sound.

Parameters:

  • float xDiff: Horizontal position difference from impact source
  • float yDiff: Vertical position difference from impact source
  • float xI: Incoming horizontal velocity of the impact
  • float yI: Incoming vertical velocity of the impact

Fields

public float blastForce = 50f

Physics knockback force applied to units caught in the explosion. Determines how far units are pushed away from the blast center. Defaults to 50 force units.


public int damage = 5

Base explosion damage dealt to units, terrain, and destructibles. Applied through various multipliers for different explosion zones. Defaults to 5 damage.


public DamageType damageType

Type of damage this grenade inflicts, determining how units resist or react to the explosion. Also used when damaging fragile objects during flight.


public MonoBehaviour firedBy

Reference to the unit that launched this grenade. Used for damage attribution, achievement tracking, and determining local ownership for networking. Set during initialization.


public bool friendlyFire = true

Determines if this grenade damages units on the same team as the thrower. When true, explosion damages all units. When false, only damages enemies. Defaults to true.


protected float panicCounter

Timer controlling when to trigger panic in nearby AI units. Decrements each frame when life is below 0.5 seconds, triggering Map.PanicUnits every 0.045 seconds to make enemies flee.


public int playerNum = -1

Identifies which player threw this grenade for damage attribution and scoring. Also determines trail color for players 0-3. Defaults to -1 for non-player grenades.


public float range = 48f

Explosion radius in world units. Controls the area of effect for damage to units, terrain, and doodads. Also scales visual explosion effects. Defaults to 48 units.


public bool shootable

When true, this grenade can be targeted and detonated by projectiles. Registers with Map.RegisterShootableGrenade for AI targeting systems.


Special Abilities

Methods

internal void GiveBrotatoAchievementOnKill()

Marks this grenade to award the Hot Brotato achievement if it kills a mook. Called by special abilities or power-ups that enable achievement-granting grenades.


Fields

protected bool giveBrotatoAwardIfIKillAMook

When true, awards the Hot Brotato achievement if this grenade kills a mook enemy. Checked during explosion damage and enemy bounce kills. Set via GiveBrotatoAchievementOnKill method by special abilities or power-ups.


protected bool giveMartiniAchievement

When true, awards the Martini achievement when this grenade kills enemies by bouncing off them. Only triggers during successful enemy bounce kills, not regular explosions.


Position & Physics

Methods

protected override void Bounce(bool bounceX, bool bounceY)

Handles physics response when the grenade hits surfaces. Reduces velocities, applies angular friction for realistic rolling, interacts with doors, triggers ground effects like mines, and plays impact sounds based on collision force.

Parameters:

  • bool bounceX: True if bouncing on the X axis (hit vertical surface)
  • bool bounceY: True if bouncing on the Y axis (hit horizontal surface)

protected virtual void BounceOffEnemies()

Processes bouncing off enemy units when the grenade hits them from above. Checks if the grenade has sufficient downward velocity, then attempts to hit units below. Supports both single and multiple bounce modes. Applies upward velocity based on weight and reduces horizontal speed. Awards achievements for special bounce kills.


protected virtual bool CanBounceOnEnemies()

Determines if the grenade has sufficient downward velocity to bounce off enemies. Prevents slow-moving grenades from triggering enemy bounces.

Returns:

  • bool: True if downward velocity exceeds 120 units/second

protected virtual void HitFragile()

Detects and damages fragile objects in the grenade's path during flight. Uses velocity direction to check ahead for breakable objects on the fragile layer. Creates visual puff effects on impact and either bounces off doors or sends damage messages to other fragile objects like glass.


public override void Launch(float newX, float newY, float xI, float yI)

Primary method for spawning and launching grenades into the world. Handles complex wall collision detection to prevent grenades from spawning inside terrain. Registers the grenade as a fetchable object for AI awareness and initializes trail tracking.

Parameters:

  • float newX: Initial X position
  • float newY: Initial Y position
  • float xI: Initial horizontal velocity
  • float yI: Initial vertical velocity

public void ReduceLife(float launchLifeM)

Multiplies the grenade's remaining fuse time by the specified factor. Used to create shorter fuses for special grenade types or launch methods. Ensures a minimum life of 0.01 seconds to prevent instant detonation.

Parameters:

  • float launchLifeM: Multiplier for the remaining life (0-1 reduces, >1 extends)

protected override void RunMovement()

Updates grenade physics each frame. Checks for collisions with fragile objects, handles bouncing off enemies if enabled, and processes base movement physics.


public void SetMinLife(float amount)

Ensures the grenade has at least the specified fuse time remaining. Used to prevent instant explosions when grenades are thrown or knocked.

Parameters:

  • float amount: Minimum life time in seconds

public override void SetPosition()

Updates the grenade's transform position. Simple override that calls the base implementation to maintain position synchronization.


public virtual void ThrowGrenade(float XI, float YI, float newX, float newY, int _playerNum)

Launches a grenade that was previously held by a unit. Unparents the grenade, sets its position and velocity, resets visual effects, and ensures a minimum fuse time of 0.7 seconds.

Parameters:

  • float XI: Horizontal throw velocity
  • float YI: Vertical throw velocity
  • float newX: Release X position
  • float newY: Release Y position
  • int _playerNum: Player number who threw the grenade

Properties

public override bool ShouldTimeslice { get; set; }

Indicates that grenades should not participate in time-slicing optimization. Always returns false to ensure grenades update every frame for accurate physics and timing.


Fields

protected List<Unit> alreadyBouncedOffUnits

Tracks units this grenade has bounced off when bounceOffEnemiesMultiple is false. Prevents the same unit from being hit multiple times. List is populated during BounceOffEnemies calls.


public float angularFrictionM = 1f

Multiplier for angular velocity calculations when useAngularFriction is enabled. Higher values create more spin from movement and impacts. Defaults to 1.0.


public bool bounceOffEnemies

Enables the grenade to bounce off enemy units when falling from above. Checked each frame during movement updates to trigger bounce detection.


public bool bounceOffEnemiesMultiple

When true, allows bouncing off the same enemy multiple times. When false, uses alreadyBouncedOffUnits list to track and prevent repeated bounces.


protected float bounceYOffset = 2f

Vertical offset applied during enemy bounce detection. Adjusts the collision check position relative to the grenade center. Defaults to 2 units upward.


protected LayerMask fragileLayer

Layer mask for detecting breakable objects like glass during flight. Set to "DirtyHippie" layer during initialization. Used by HitFragile method for collision detection.


public bool useAngularFriction

Enables realistic rotation physics when bouncing. When true, horizontal movement creates rotation and impacts affect spin based on the angularFrictionM multiplier.


public float weight = 1f

Mass factor affecting physics calculations. Higher weight reduces knockback effects and bounce height. Used in velocity calculations for both throwing and impact responses. Defaults to 1.0.


Animation & Sprite Systems

Methods

private void CreateWarningEffect()

Spawns a red warning diamond effect at the grenade's position. Creates either a normal or large warning indicator based on the largeWarning flag setting.


protected virtual void MakeEffects()

Creates explosion visual and audio effects when the grenade detonates. Spawns either a huge or normal explosion based on the hugeExplosion flag, plays the death sound, and damages nearby destructible doodads.


public void ResetTrail()

Resets trail effect tracking to the current position. Prevents visual artifacts when the grenade is teleported or initially thrown by clearing the trail history.


protected virtual void RunTrail()

Updates the grenade's visual trail effect each frame. Supports two trail types: FireTrail creates spark particles along the path, while ColorTrail creates a colored line based on the throwing player's color and grenade velocity. Includes optimization to prevent excessive trail length.


protected virtual void RunWarnings()

Creates visual and audio warnings before explosion. Increases warning intensity as the fuse burns down, with faster flickering and higher pitch beeps when life drops below 0.5 seconds. Alternates grenade material and creates warning diamonds. Also triggers AI unit panic reactions.


Fields

protected ProjectileTrail createdTrail

Reference to the active ProjectileTrail effect instance. Created when the grenade has sufficient velocity and destroyed when velocity drops too low. Used for ColorTrail type.


public bool dontMakeEffects

When true, skips creating visual explosion effects in the Death method. Used for silent explosions or when effects are handled externally.


public Puff explosion

Standard explosion visual effect component. Assigned in Unity Inspector and likely triggered during the Death method for normal-sized explosions.


public Puff explosionBig

Large explosion visual effect component. Assigned in Unity Inspector and likely triggered for grenades with enhanced explosion visuals.


public FlickerFader fire1

Visual fire effect component slot 1. Assigned in Unity Inspector for grenades with burning or fire trail effects. Controlled by FlickerFader component behavior.


public FlickerFader fire2

Visual fire effect component slot 2. Assigned in Unity Inspector for grenades with burning or fire trail effects. Controlled by FlickerFader component behavior.


public FlickerFader fire3

Visual fire effect component slot 3. Assigned in Unity Inspector for grenades with burning or fire trail effects. Controlled by FlickerFader component behavior.


protected float flickerCounter

Timer controlling the material swap rate for warning flashes. Increments each frame and triggers flashes at 0.0667 second intervals when life is below 0.5 seconds, or 0.133 second intervals otherwise.


public bool hasHeroTrail

Flag indicating this grenade should display a hero-colored trail. Currently unused in base class but available for derived grenade types.


public bool hugeExplosion

When true, creates an enhanced explosion effect with additional visual elements and low-pass audio filtering. Used for special high-powered grenades.


public float hugeExplosionLowPassM = 0.1f

Audio low-pass filter multiplier applied to huge explosion sound effects. Lower values create more muffled, bass-heavy explosion sounds. Used when hugeExplosion is true. Defaults to 0.1 for deep, rumbling explosions.


public bool largeWarning

When true, displays a larger warning diamond effect during countdown. Used for grenades with larger blast radius or special importance. Standard grenades use the normal size.


protected float lastTrailAlphaM = 0.1f

Alpha transparency multiplier for trail effects. Set to 0.5 when trail is reset, though current implementation doesn't actively use this value. Defaults to 0.1. Reserved for future trail fading effects.


protected float lastTrailX

Stores the X coordinate where the last trail segment was drawn. Used to calculate distance between trail points and prevent excessive trail length. Updated continuously during trail rendering.


protected float lastTrailY

Stores the Y coordinate where the last trail segment was drawn. Works with lastTrailX to track trail continuity and calculate segment distances for optimization.


protected Material mainMaterial

The grenade's default visual material cached from the renderer at startup. Used for material swapping during warning flashes before explosion.


protected bool mainMaterialShowing = true

Tracks which material is currently displayed during warning flashes. Toggles between true (main material) and false (other material) to create the flickering countdown effect before explosion. Defaults to true.


public Material otherMaterial

Alternate material for visual warning effects. Swapped with mainMaterial during the countdown phase to create a flashing warning effect before detonation.


protected int pulseCount

Counts the number of warning flashes during countdown. Used to trigger warning effects and beep sounds on odd-numbered pulses, creating a rhythmic warning pattern.


public Shrapnel shrapnel

Reference to shrapnel projectile prefab. Assigned in Unity Inspector for grenades that spawn shrapnel on explosion. Used by derived grenade types.


public Puff smoke1

Smoke visual effect component slot 1. Assigned in Unity Inspector for smoke trails or explosion smoke. Likely triggered on explosion or during flight.


public Puff smoke2

Smoke visual effect component slot 2. Assigned in Unity Inspector for smoke trails or explosion smoke. Likely triggered on explosion or during flight.


private int trailDrawDelay

Frame counter that delays trail drawing after launch. Set to 2 frames on launch to prevent trail artifacts at spawn point. Decrements each frame until reaching 0.


public CustomLineRenderer trailRenderer

Line renderer component for drawing colored trails. Configured in SetupGrenade to match the throwing player's color. Null for grenades without colored trails.


public TrailType trailType

Determines the visual trail style for this grenade. FireTrail creates spark particles along the flight path, while ColorTrail creates a colored line based on the throwing player.


Audio System

Methods

protected virtual void PlayDeathSound(float v)

Plays the grenade explosion sound effect at the default volume of 0.7.


protected virtual void PlayDeathSound(float v)

Plays the grenade explosion sound effect at the specified volume level.

Parameters:

  • float v: Volume level for the explosion sound (0.0 to 1.0)

protected virtual void PlaySpecialSound(float v)

Plays special grenade sound effects positioned between the grenade and camera for better audibility. Used for unique grenade effects like cluster bomb separations.

Parameters:

  • float v: Volume level for the special sound (0.0 to 1.0)

Fields

public float maxVelocityBounceVolume = 210f

Impact velocity at which bounce sounds reach maximum volume. Used to scale volume between minimum and maximum based on impact force. Defaults to 210 units per second.


public float minVelocityBounceSound = 33f

Minimum impact velocity required to play bounce sound effects. Prevents sounds from playing on gentle contacts. Defaults to 33 units per second.


protected Sound sound

Cached reference to the global Sound instance. Lazily initialized when first playing death sounds to avoid repeated GetInstance() calls. Used for performance optimization when playing explosion audio.


public SoundHolder soundHolder

Container for all grenade-related sound effects including defend sounds (knockback), hit sounds (bouncing), death sounds (explosion), special sounds, and greeting sounds (countdown beeps). Central audio management for the grenade.


Networking & RPC

Methods

public override UnityStream PackState(UnityStream stream)

Serializes the grenade's network state for synchronization. Packs the X/Y position and enabled state into the stream, then calls base packing for additional data.

Parameters:

  • UnityStream stream: The network stream to write state data to

Returns:

  • UnityStream: The stream with serialized grenade state

public override UnityStream UnpackState(UnityStream stream)

Deserializes the grenade's network state from a stream. Reads position and enabled state, applies them to the grenade, then calls base unpacking for additional data.

Parameters:

  • UnityStream stream: The network stream to read state data from

Returns:

  • UnityStream: The stream after reading grenade state

Properties

public bool FiredLocally { get; set; }

Determines if this grenade was fired by the local player rather than a remote networked player. Uses lazy evaluation to check if the firedBy unit is owned locally, falling back to the grenade's own ownership. Critical for preventing duplicate damage calculations in multiplayer.


Helper & Utility

Methods

public void RunUpdate()

Allows external code to force an immediate update cycle. Simply calls the Update method to process physics and effects outside the normal update loop.


protected override bool Update()

Main update loop called each frame. Processes base physics updates, runs warning effects when the fuse is below 1 second, and updates the visual trail.

Returns:

  • bool: Always returns true to continue updating

⚠️ **GitHub.com Fallback** ⚠️