Here is a picture of my game:
I use a multidimensional array to place the tiles of the walls, the enemies, coins and player in their initial positions. I then use this array to determine if enemies or the player can enter a position. If the position they are wanting to move in is not a wall, then it can be made. I make use of object.transform() to change the position of the enemies & players, and update the multidimensional array to store their new positions.
I am using a non-physical collision technique in order to determine if the player has collided with an enemy or a coin. However, sometimes the game just doesn’t register the player hitting a coin. The coin just stays there, without the score going up.
Here is my code for the collision detection of the player & coins specifically:
for i = 1, #coinCache, 1 do -- Check for collision between player and this coin instance if ( coinCache[i] and hasCollidedRect( player, coinCache[i] ) ) then score = score + 1 -- Remove the coin from the screen display.remove( coinCache[i] ) -- Remove reference from table coinCache[i] = nil -- Handle other collision aspects like increasing score, etc. if score >= 10 then gotoLevelWon() timer.cancelAll() end end end
And here is the function used within that code:
local function hasCollidedRect( obj1, obj2 ) if ( obj1 == nil ) then -- Make sure the first object exists return false end if ( obj2 == nil ) then -- Make sure the other object exists return false end local left = obj1.contentBounds.xMin+1 <= obj2.contentBounds.xMin+1 and obj1.contentBounds.xMax-1 >= obj2.contentBounds.xMin+1 local right = obj1.contentBounds.xMin+1 >= obj2.contentBounds.xMin+1 and obj1.contentBounds.xMin+1 <= obj2.contentBounds.xMax-1 local up = obj1.contentBounds.yMin+1 <= obj2.contentBounds.yMin+1 and obj1.contentBounds.yMax-1 >= obj2.contentBounds.yMin+1 local down = obj1.contentBounds.yMin+1 >= obj2.contentBounds.yMin+1 and obj1.contentBounds.yMin+1 <= obj2.contentBounds.yMax-1 return ( left or right ) and ( up or down ) end
Any help would be appreciated.