PcoWSkbVqDnWTu_dm2ix
Using Particles for Explosions
Part 2 - Emitting Particles with Scripts
Using Particles for Explosions
Part 2 - Emitting Particles with Scripts

With the emitter complete, the explosion can now be played through a script.

Script Setup

The script works by checking for players touching the trap. Whenever it detects someone, the particles will emit and the player will die.

  1. In the trap part, add a new Script named PlayExplosion.

    alt

  2. Set up variables to store the part and emitter. Then, include a variable named EMIT_AMOUNT that stores the number of particles emitted per explosion.

    local trapObject = script.Parent
    local particleEmitter = trapObject:FindFirstChild("Explosion")
    
    local EMIT_AMOUNT = 100
  3. Code an event to check if a Humanoid touches the part. If so, set that humanoid’s health to 0, forcing them to respawn.

    local trapObject = script.Parent
    local particleEmitter = trapObject:FindFirstChild("Explosion")
    
    local EMIT_AMOUNT= 30
    
    local function killPlayer(otherPart)
        local character = otherPart.Parent
        local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    
        if humanoid then
            humanoid.Health = 0
        end
    end
    
    trapObject.Touched:Connect(killPlayer)

Play the Explosion

In scripts, particles are emitted using the Emit() function. This creates a one-time burst of a number of particles.

  1. Call the Emit() function and pass in EMIT_AMOUNT, the variable created earlier.

    local trapObject = script.Parent
    local particleEmitter = trapObject:FindFirstChild("Explosion")
    
    local EMIT_AMOUNT= 100
    
    local function killPlayer(otherPart)
        local character = otherPart.Parent
        local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    
        if humanoid then
            humanoid.Health = 0
            particleEmitter:Emit(EMIT_AMOUNT)
        end
    end
    
    trapObject.Touched:Connect(killPlayer)
  2. Test the script by walking into the trap.

With just a few changes to the example in this course, you can create a variety of different effects. Some alternatives include sparkles for gathering collectable objects, or explosions to indicate a projectile’s impact.


Previous Page Getting Started