Problem to detect sword collision

Started by Diarandor, August 26, 2015, 04:14:15 AM

Previous topic - Next topic
Hi! I am having problems to detect a custom entity (a plant) when it is cut by the sword. The code I am using is something like this:

entity:add_collision_test("sprite", function(entity, other_entity, sprite, other_sprite)
  -- Do nothing if the animation is not "sword", or if the sword is not close enough.
  if other_sprite == nil then return end
  if other_sprite:get_animation() ~= "sword" then return end
  -- cut the plant!
end)

I realized that when the hero was in down direction, he could cut a plant that was in the up direction, and I didn't know why that did happen until now (because the sword sprite was not colliding with the plant).

I found that the problem is that, when the hero attacks, both the hero and the sword have an animation called "sword", so if the hero sprite touches the plant during the attack, the plant is cut too (even if the sword does not touch it). I also tried using the method get_type, but the collision with the sword sprite seems to return "hero" as the type of the entity (I suppose that the sword is just a sprite of the hero).

Is there some way to deal with this problem quickly? As a last option I would change the sword item by a custom entity sword, but I want to keep the sword item if possible, for simplicity.
"If you make people think they're thinking, they'll love you. But if you really make them think, they'll hate you."

Well, I finally solved my own problem... XD
This is part of the code I used for the "plant" custom entity that can be cut by the sword:

function entity:on_created()
  -- Set properties.
  local map = self:get_map()
  self:set_traversable_by(false)
  -- Cut the entity when the sword hits it.
  entity:add_collision_test("sprite", function(entity, other_entity, sprite, other_sprite)
    -- Do nothing if the animation set is not of the sword, or if the sword is not close enough.
    if other_sprite == nil then return end
    local animation_set = other_sprite:get_animation_set()
    local sword_id = map:get_hero():get_sword_sprite_id()
    if animation_set ~= sword_id then return end
    if entity:get_distance(other_entity) > 28 then return end -- Set a max distance to cut.
    entity:cut() -- Cut the plant.
  end)
end
"If you make people think they're thinking, they'll love you. But if you really make them think, they'll hate you."

Can't you use the same system that works with the sword collision on walls to find weak walls that can be bombed?

I don't know, because I never made a wall that can be bombed. I just wanted to destroy some custom entities (plants) with the sword, and I didn't find a better way to do it, so I will keep that code
"If you make people think they're thinking, they'll love you. But if you really make them think, they'll hate you."