Hi,
I have been wanting to create a simple mechnaic so when the enemys come in they touch the character and then they get removed from the table. I think it’s not changing the table so when it loops back through it’s nil and it’s coming up with the error about the objects being nil in the calculate angle.
--------
display.setStatusBar( display.HiddenStatusBar )
system.activate( "multitouch" )
-- Load Joystick Class
local physics = require( "physics" )
local movieclip = require("movieclip")
physics.start()
physics.setGravity(0, 0)
physics.setDrawMode( "hybrid" )
--local background = display.newImage( "background.png" )
local enemys = {}
local enemyssize = 0
local velocity = 0.5
local characters = {}
local characterssize = 0
local function gameTick()
for i=1, enemyssize, 1 do
local angle = calculateAngle(enemys[i].x, enemys[i].y,
characters[1].x, characters[1].y)
enemys[i].x = enemys[i].x + (math.cos(angle) \* velocity)
enemys[i].y = enemys[i].y + (math.sin(angle) \* velocity)
end
for i=1, enemyssize, 1 do
if (enemys[i].deathflag == true) then
enemys[i]:removeSelf()
enemys[i] = nil
if (enemyssize \> 0) then
for k=i, #enemys-1, 1 do
enemys[k] = enemys[k+1]
end
enemyssize = enemyssize - 1
else
enemyssize = 0
end
break
end
end
end
function calculateAngle(x1, y1, x2, y2)
local angle = math.atan2(y1 - y2, x1 - x2) \* 180 / 3.14159265
return angle
end
function createEnemys( spawncount )
for i=1, spawncount do
table.insert(enemys, i, display.newImage( "enemy.png" ))
enemys[i].x = math.random( 20, display.contentWidth-50 )
enemys[i].y = math.random( 20, display.contentHeight-50 )
enemys[i].myName = "enemy"
enemys[i].deathflag = false
-- Add physics
physics.addBody( enemys[i] )
enemys[i].isFixedRotation = true
i = i + 1
end
enemyssize = enemyssize + spawncount
end
function createCharacters( spawncount )
for i=1, spawncount do
table.insert(characters, i, display.newImage( "character.png" ))
characters[i].x = 50
characters[i].y = 50
characters[i].myName = "character"
-- Add physics
physics.addBody( characters[i] )
characters[i].isFixedRotation = true
i = i + 1
end
characterssize = characterssize + spawncount
end
local function onCollision( event )
if ( event.phase == "began" ) then
if (event.object1.myName == "enemy" and
event.object2.myName == "character") then
event.object1.deathflag = true
end
end
end
Runtime:addEventListener( "collision", onCollision )
Runtime:addEventListener( "enterFrame", gameTick )
createEnemys(5)
createCharacters(1)
I have tryed using this method for deleting aswell as using table.remove(enemys, i) and also various other methods with zero luck.
Any help would be appricated.
Thanks. [import]uid: 22223 topic_id: 15569 reply_id: 315569[/import]
[import]uid: 3826 topic_id: 15569 reply_id: 57524[/import]