Function for when a part is destroyed

  • Vondaniel
    16th Mar 2017 Member 0 Permalink

    Is there a way to run a function when a part is destroyed? I'm trying to limit the amount of particles of a certain type there can be without luck. 

  • LBPHacker
    16th Mar 2017 Developer 0 Permalink

    Not really. The best you can do is register a step handler and reset a per-frame counter to 0, then increment it from the update function of the particle. The update function can just sim.partKill the particle instead of incrementing the counter if it's too high. This of course means that particles would still be created, they just wouldn't get the chance to live a single frame.

     

    This approach is by no means multi-threading-friendly, but when it comes to TPT, that's the least of your concerns. A bigger problem is that this approach will kill the particles with higher IDs, since they're evaluated later (their Update function is called later) than that of particles with lower IDs. This would happen even if the particles on screen had higher IDs and you spawned a bunch new with lower IDs. The new ones would kill the old ones.

     

    This can be fixed by marking the particles as "old" once they survive one Update function, and then only try to kill particles which are not marked "old". Try this:

     

    local dmnd_max = 100
    local dmnd_count
    tpt.register_step(function()
        dmnd_count = 0
    end)
    elem.property(elem.DEFAULT_PT_DMND, "Update", function(partID)
        if dmnd_count == dmnd_max and sim.partProperty(partID, "tmp") == 0 then
            sim.partKill(partID)
            return
        end
        dmnd_count = dmnd_count + 1
        sim.partProperty(partID, "tmp", 1)

        -- the rest of the update function
    end)

    Edited once by LBPHacker. Last: 16th Mar 2017
  • jacob1
    17th Mar 2017 Developer 2 Permalink
    There is also sim.elementCount() to get the number of particles of a certain element
    Edited once by jacob1. Last: 17th Mar 2017
  • Vondaniel
    17th Mar 2017 Member 0 Permalink

    that is exactly what i needed jacob1, thank you!

  • QuanTech
    17th Mar 2017 Member 0 Permalink

    @LBPHacker (View Post)

     Feels bad man

  • LBPHacker
    19th Mar 2017 Developer 0 Permalink

    Well, nah, actually it doesn't. It's just that, based on experience *cough*, I assumed that something as obvious as Simulation::elementCount would not be accessible from Lua. That's how it usually is. So when an assumption like that turns out to be a misconception, it doesn't feel that bad.

     

    Epic fail nonetheless :P

    Edited once by LBPHacker. Last: 19th Mar 2017