I am having problems changing the Image of an object after a collision.
Purpose is to change the image of a block to the image of a damaged block after colliding with an enemy.
I have a function:
newShape ( kind, x, y, health )
if ( kind == 1 ) then
if ( health == 2 ) then
shape = display.newRect ( xxxxx );
shape.health = 2;
localGroup:insert ( shape );
physic.addBody ( shape, {xxx} );
elseif ( health == 1 ) then
shape = display.newRect ( xxxxx );
shape.health = 1;
localGroup:insert ( shape );
physic.addBody ( shape, {xxx} );
end
end
end
so that is how I am creating my shapes, they are then stored in a table:
local shapeObjects = {}
shapeObject[i] = newShape ( kind, x, y, health );
shapeObject[i].index = i;
and then I have a collision:
function onCollision ( self, e )
if ( e.phase == "began" ) then
timer.performWithDelay ( 100, updateHealth ( e.other, self );
end
end
enemy.collision = onCollision;
enemy:addEventListener ( "collision", enemy );
The collision outsources to another function which controls the image swapping
function updateHealth ( shape, enemy )
local health = shape.health - enemy.damage;
local index = shape.index;
local kind = shape.kind;
local x = shape.x;
loca; y = shape.y;
if ( health > 0 ) then
shape:removeSelf ();
-- Here is where the program is having a problem and crashes.
shapeObject[index] = newShape ( kind, x, y, health );
elseif ( health >= 0 ) then
shape:removeSelf ();
end
end
So I can remove that line of code and everything works fine. I have also tried having the program create a simple rectangle of a new name:
tempShape = display.newRect ( xxxx );
But if I try to add it to a group or add it as a physical body, the program crashes.
I read that you have to have a timer delayed to make modification or remove objects during a collision, but I have done this and still every time it crashes and I have tried almost everything.
Any ideas on an alternative or a fix to my problem