Collision question

Hello,
I am trying to substract hero.hp value when zombie and hero are colliding, but
this method doesn’t work correctly.

  1. On first collision it substracts hero.hp value only one time
  2. on second collision it substracts hero.hp value while it’s colliding and after collision(I need it to substract hero.hp value only till collision ends)

My method:

local function zombieCollision(self, event)

  if event.phase == "began" then

    if event.other == hero then

      hero.hp = hero.hp - 10
      hp.text = "Hp:"..hero.hp

      timer.performWithDelay(500, check)

       function check()
        if event.phase == "ended" then
          print("ended")
        else
          hero.hp = hero.hp - 10
          hp.text = "Hp:"..hero.hp
          timer.performWithDelay(500, check)

        end
      end
    end
  end
end

You can’t check the same event for a phase change like you’re doing, because the phase of an event never changes. What happens in your code is:

  1. When collision begins, you reduce the hero’s hp by 10, and schedule the function check() to run after 500ms.
    1.1 When check() runs after 500ms, phase is still “began”, and therefore you reduce hp by 10 again and reschedule the check() function to run again in 500ms.
    1.2 event.phase will never be “ended”, so the check() function will continue to run forever every 500ms…
  2. When collision ends, you get a new event and again reduce hp by 10 and schedule check() to run after 500ms
    2.1 This time, event.phase will be “ended”, and check() will therefore do nothing and never run again.

What you want do do is something like this, given that you want to reduce hp by 10 every 500 ms while objects are colliding:

-- Define a function that handles hp reduction and
-- reschedules itself every 500ms while collision is ongoing
local checkHeroCollision
checkHeroCollision = function()
  if hero.isColliding then
    hero.hp = hero.hp - 10
    hp.text = "Hp:"..hero.hp
    timer.performWithDelay(500, checkHeroCollision)
  end
end

local function zombieCollision(self, event)
  if event.other == hero then
    if event.phase == "began" then
      -- This will start the hp handler
      hero.isColliding = true
      checkHeroCollision()
    elseif event.phase == "ended"
      -- And this stops the hp handler
      hero.isColliding = false
    end
  end
end
2 Likes

Thank you. :slight_smile: