Search code examples
mobilecollision-detectioncollisioncoronasdk

Stopping physics body from movement in Corona SDK


I'm learning Corona SDK and I'm making small project in that purpose.

So, my problem is next one: I managed to create 2 physics objects and make one of them "explode" when it collides with the other one. My question is how to make other object (it has linear impulse applied) stop when it collides? Also, when it stops, it has to be removed from the screen to avoid colliding with other objects...

Here is a part with removing first object on collision:

nloDrop = function()
local nlo = display.newImageRect("nlo.png", 65, 25)
nlo.x = 35 + mRand(410) ; nlo.y = -60
physics.addBody(nlo, "dynamic", {density=1, bounce = 0, friction = 0, filter = {maskBits = 4, categoryBits = 2}})
nlo:applyLinearImpulse(0, 0.8, nlo.x, nlo.y)
nlo.isSensor = true
nlo.collision = nloCollision
nlo:addEventListener("collision", nlo)
nlo.name = "nlo"
toFront()

end

And here is 'collision' function:

function nloCollision(self, event)
if ((event.other.myName == "weaponName") then
    print("funkc")
    self:removeSelf()
    self:removeEventListener("collision", nlo)
    self = nil
    if weapon ~= nil then
        -- stop moving of weapon
    end
end

end

Thanks!


Solution

  • I made it setting the object like local variable and making a function that deletes/removes each variable (object) after some interaction or collision.

    1st function contains object creating (that is a local type under function) and applying physics to that object. 2nd function contains deleting (self:removeSelf()) that works because each object is object for itself and when deleting it, physics stuff will continue to work because new local object is going to be created.

    function create(event)
        local weap1 = display.newImage("weap1.png", 0, 0)
        weap1.x = turret.x ; weap1.y = turret.y
        weap1.rotation = turret.rotation
        weap1.collision = weap1Collision
        weap1:addEventListener("collision", weap1)
        physics.addBody(weap1, "dynamic", {density = 1, friction = 0, bounce = 0, filter = {maskBits = 2, categoryBits = 4}})
        weap1:applyLinearImpulse(forceWeap1*xComp, forceWeap1*yComp, weap1.x, weap1.y)
    
    function weap1Collision(self,event)
        if (event.other.name == "collisionObject") then
            self:removeSelf()
            self:removeEventListener("collision", weap1)
            self = nil
        end
    end
    

    local type of variable (object) makes it work.

    P.S.: vanshika, thanks for your answer, it's useful ;)