Attempt to compare nil with number on (i).x < 100 then - lua

I am trying to spawn a new display.newRect if to old one is < 100 but I'm getting a 'Attempt to compare nil with number'
function hollSpawne(i)
if (i).x < 100 then
hollspawn()
end
end
HollControll = timer.performWithDelay( 1400 , hollSpawne, 0 )
I cant see the error, could someone please explain how to fix this ?
Fullcode :
function pluspoint(i)
score = score + 1
display.remove(i)
end
screenGroup = self.view
holl = {}
hollSpawn = function()
i = display.newRect( 0, 0, math.random(10, 500), 53 )
i.x = display.contentWidth + i.contentWidth + 10
i.y = display.contentHeight - 53/2
i:setFillColor( 1, 0, 0 )
i.name = "hollgameover"
physics.addBody(i, "static", {density=.1, bounce=0.5, friction=.2,filter=playerCollisionFilter } )
trans55 = transition.to(i,{time=2000, x=display.contentWidth - display.contentWidth - i.contentWidth/2 - 20, onComplete=pluspoint, transition=easing.OutExpo } )
holl[#holl+1] = i
screenGroup:insert(i)
end
timereholl = timer.performWithDelay( 100 , hollSpawn, 1 )
function hollSpawne(i)
if (i).x < 100 then
hollspawn()
end
end
HollControll = timer.performWithDelay( 1400 , hollSpawne, 0 )
-
-
new test still not working
screenGroup = self.view
holl = {}
hollSpawn = function()
i = display.newRect( 0, 0, math.random(10, 500), 53 )
i.x = display.contentWidth + i.contentWidth + 10
i.y = display.contentHeight - 53/2
i:setFillColor( 1, 0, 0 )
i.name = "hollgameover"
physics.addBody(i, "static", {density=.1, bounce=0.5, friction=.2,filter=playerCollisionFilter } )
trans55 = transition.to(i,{time=2000, x=display.contentWidth - display.contentWidth - i.contentWidth/2 - 20, onComplete=pluspoint, transition=easing.OutExpo } )
holl[#holl+1] = i
screenGroup:insert(i)
end
timereholl = timer.performWithDelay( 100 , hollSpawn, 1 )
function hollSpawne(event)
if (i).x < 100 then
hollSpawn()
end
end
HollControll = timer.performWithDelay( 1400 , hollSpawne, 0 )

Your timer calls hollSpawne with no arguments, but in function you use 'i' parameter.
Try this one:
local function hollSpawne(i)
if i.x < 100 then
hollspawn()
end
end
HollControll = timer.performWithDelay( 1400 , function()
hollSpawne(my_i_value)
end, 0 )

The timer calls the listener with event as argument so i is an event. Since i is a global you can just have the arg be event:
function hollSpawne(event)
if (i).x < 100 then
hollSpawn()
end
end
Note that I use hollSpawn not hollspawn as I think this is a typo that will cause additional bug.
Sidenote on style: not sure why you need () around i, un-Lua'ish. Also you probably should declare i local to your module:
local i
screenGroup = self.view
holl = {}
hollSpawn = function()
i = display.newRect( 0, 0, math.random(10, 500), 53 )
...

Related

ERROR: attempt to index global 'square' (a nil value)

I have been googling the crap out of this error (attempt to index global 'square' (a nil value)), but I can't seem to understand what the problem is... I know it should be fairly easy to fix but I can't figure it out for the life of me. The error is occurring at the very bottom, I marked the problem.
enter code here
local backdrop = display.setDefault("background", 1, 1, 1)
local physics = require("physics")
physics.start()
_W = display.contentWidth; -- Get the width of the screen
_H = display.contentHeight; -- Get the height of the screen
motionDown = 0;
motionUp = 0;
motionRight = 0;
motionLeft = 0;
motionSquare = 5
speed = 4
local left = display.newRect(0,0,_W/2,_H/1.19)
left.x = _W/4.5; left.y = _H/2;
local right = display.newRect(0,0,_W/2,_H/1.19)
right.x = _W/1.25; right.y = _H/2;
local top = display.newRect(0,0,_W,_H/5.5)
top.x = _W/2; top.y =0;
local bottem = display.newRect(0,0,_W,_H/5.5)
bottem.x = _W/2; bottem.y =_H;
player = display.newImage("player.png", display.contentCenterX, display.contentCenterY)
player.x = math.random(10,_W-10)
player.y = math.random(10,_H-10)
player:toFront(player)
physics.addBody( player, "static" )
function left:tap()
motionDown = 0;
motionUp = 0;
motionRight = 0;
motionLeft = -speed;
local square = display.newRect( 0, 0, 5, 5 )
square.strokeWidth = 3
square:setFillColor( 0 )
square:setStrokeColor( 0, 0, 0 )
square.x = player.x + 10 ; square.y = player.y;
local function moveSquare (event)
square.x = square.x + motionSquare;
end
Runtime:addEventListener("enterFrame", moveSquare)
end
left:addEventListener("tap",left)
function right:tap()
motionDown = 0;
motionUp = 0;
motionLeft = 0;
motionRight = speed;
local square = display.newRect( 0, 0, 5, 5 )
square.strokeWidth = 3
square:setFillColor( 0 )
square:setStrokeColor( 0, 0, 0 )
square.x = player.x - 10 ; square.y = player.y;
local function moveSquare (event)
square.x = square.x - motionSquare;
end
Runtime:addEventListener("enterFrame", moveSquare)
end
right:addEventListener("tap",right)
function top:tap()
motionDown = 0;
motionRight = 0;
motionLeft = 0;
motionUp = -speed;
local left = display.newRect(0,0,5,5)
local square = display.newRect( 0, 0, 5, 5 )
square.strokeWidth = 3
square:setFillColor( 0 )
square:setStrokeColor( 0, 0, 0 )
square.x = player.x ; square.y = player.y + 10;
local function moveSquare (event)
square.y = square.y + motionSquare;
end
Runtime:addEventListener("enterFrame", moveSquare)
end
top:addEventListener("tap",top)
function bottem:tap(event)
motionRight = 0;
motionUp = 0;
motionLeft = 0;
motionDown = speed;
local square = display.newRect( 0, 0, 5, 5 )
square.strokeWidth = 3
square:setFillColor( 0 )
square:setStrokeColor( 0, 0, 0 )
square.x = player.x ; square.y = player.y - 10;
local function moveSquare (event)
square.y = square.y - motionSquare;
end
Runtime:addEventListener("enterFrame", moveSquare)
end
bottem:addEventListener("tap",bottem)
--Our player isn’t quite moving yet. We’ve set up the listeners to move the character left or right, but now we actually have to make him move. We do this with a Runtime Event Listener that will move the guy along the x axis.
-- Move character
local function movePlayer (event)
player.x = player.x + motionRight;
if player.x > display.contentWidth then player.x = 0
end
end
Runtime:addEventListener("enterFrame", movePlayer)
local function movePlayer (event)
player.x = player.x + motionLeft;
if player.x < 0 then player.x = display.contentWidth
end
end
Runtime:addEventListener("enterFrame", movePlayer)
local function movePlayer (event)
player.y = player.y + motionUp;
if player.y > display.contentHeight then player.y = 0
end
end
Runtime:addEventListener("enterFrame", movePlayer)
local function movePlayer (event)
player.y = player.y + motionDown;
if player.y < 0 then player.y = display.contentHeight
end
end
Runtime:addEventListener("enterFrame", movePlayer)
if square.y > display.contentHeight then square.y = 0 ### This is the
error
end
This is scope related problem. Unlike global variables, local variables have their scope limited to the block where they are declared. So your square variable is accessible only in those four function: bottem, top, left and right.
Simple solution require use forward declaration:
-- Top of file
local square
-- Later in the code you use only name of variable without local key word
Read more:
Scope for Beginners,
Faster Lua Code Using Forward Declarations in Corona SDK (youtube video),
Forward Declarations.

Attempt to index global "self"(a nil value)

I ran this code and it gave me an error attempt to index global 'self' (a nil value), in this scene i'm creating the Question1 of the game, inside which includes creating cannon, balloons and other game elements. I checked but i'm not sure whats wrong here.
function scene.createScene()
local group = self.view ---line 27 where i got the error
scoreText = display.newText( "0", 0, 0, globals.font.bold, 32 )
scoreText.x = display.contentCenterX
scoreText.y = 32
group:insert( scoreText )
background = display.newImage( "bkg_clouds.png")
group:insert(background)
background.x = 240
background.y = 195
questionText = display.newText('a', display.contentCenterX, display.contentWidth/4, native.systemFont, 40)
group:insert(questionText)
infoBar = display.newImage ("infoBar.png")
group:insert(infoBar)
background.x = 200
background.y = 100
restartBtn = display.newImage ("restartBtn.png")
group:insert(restartBtn)
background.x = 470
background.y = 300
cannon = display.newImage ("cannon.png")
group:insert(cannon)
background.x = 10
background.y = 270
cannon.anchorX = 0.5
cannon.anchorY = 0.5
restartBtn.isVisible = true
function createBalloons(a, b)
for i = 1, a do
for j = 1, b do
local balloon = display.newImage ('balloon_fat_red.png', 465+ (i * 30), 80 + (j * 50))
balloon.balloonText1 = display.newText(hiragana_array[x+1], 495, 125)
balloon.balloonText2 = display.newText(hiragana_array[x+2], 495, 175)
balloon.balloonText3 = display.newText(hiragana_array[x+3], 495, 225)
balloon.balloonText1:setFillColor( 1,1, 0 )
balloon.balloonText2:setFillColor( 1,1, 0 )
balloon.balloonText3:setFillColor( 1,1, 0 )
balloon.name = 'balloon'
physics.addBody(balloon)
balloon.bodyType = 'static'
table.insert(balloons, balloon)
end
end
target.text = #balloons
end
function cannonCharge:touch(e)
if(e.phase == 'began') then
impulse = 0
cannon.isVisible = true
Runtime:addEventListener('enterFrame', charge)
end
end
function charge()
local degreesPerFrame = 1
cannon.rotation = cannon.rotation - degreesPerFrame
impulse=impulse-0.2
if(cannon.rotation < -46) then
cannon.rotation = -46
impulse = -3.2
end
end
function shot:touch(e)
if(e.phase == 'ended') then
Runtime:removeEventListener('enterFrame', charge)
cannon.isVisible = false
cannon.rotation = 0
local cannonBall = display.newImage('cannon ball.png', 84, 220)
physics.addBody(cannonBall, {density = 1, friction = 0, bounce = 0})
group:insert(cannonBall)
-- Shoot cannon ball
cannonBall:applyLinearImpulse(dir, impulse, cannonBall.x, cannonBall.y )
--Collision listener
cannonBall:addEventListener ('collision', ballCollision)
end
end
function ballCollision(e)
if (e.other.name == 'balloon') then
scene.updateScore()
e.target:removeSelf()
print ('remove balloon text')
e.other:removeSelf()
audio.play(pop)
end
end
cannonBall:applyLinearImpulse(dir, impulse, cannonBall.x, cannonBall.y )
--Collision listener
cannonBall:addEventListener ('collision', ballCollision)
scene.view:insert( ballCollision )
end
You probably need function scene:createScene(). Note the colon instead of the dot in your original code.
Your function should be like this.
function scene:createScene( event )
local group = self.view
-----------------------------------------------------------------------------
-- CREATE display objects and add them to 'group' here.
-- Example use-case: Restore 'group' from previously saved state.
-----------------------------------------------------------------------------
end
Here is the reference:
http://docs.coronalabs.com/api/library/storyboard/

Flipboard Effect on Corona SDK using Lua

.
Hi, everybody,
This is not a question, is just to show the code if someone's interested on it.
I used the FLIPBOOK project presented in the Corona Share Your Code site, and changed it a little bit. (http://developer.coronalabs.com/code/flipbook-module-realistic-page-curling-effect).
The main.lua file:
-----------------------------------------------------------------------------------------
--
-- main.lua
--
-----------------------------------------------------------------------------------------
local Flipbook = require 'flipbook'
local nrPages = 6
local myFirstFlipbook = Flipbook:newFlipbook(nrPages, "mainshadow2.png" )
for x=1,nrPages do
local grp1 = display.newGroup()
--grp1:setReferencePoint( display.TopLeftReferencePoint )
local rct1 = display.newRect( 0, 0, display.contentWidth, display.contentHeight )
--grp1.isVisible = false
local txt1 = display.newText("Meu texto "..x.." ...", 2, display.contentHeight - 20, native.systemFont, 16)
txt1:setTextColor(0, 0, 0)
local img1 = display.newImageRect( "background"..x..".png",display.contentWidth/5*4,display.contentHeight/5*4 )
img1.x = display.contentWidth/2
img1.y = display.contentHeight/2
grp1:insert(rct1)
grp1:insert(img1)
grp1:insert(txt1)
local grp2 = display.newGroup()
--grp4:setReferencePoint( display.TopLeftReferencePoint )
local rct2 = display.newRect( 0, 0, display.contentWidth, display.contentHeight )
--grp1.isVisible = false
local txt2 = display.newText("Meu texto "..x.." ...", 2, display.contentHeight - 20, native.systemFont, 16)
txt2:setTextColor(0, 0, 0)
local img2 = display.newImageRect( "background"..x..".png",display.contentWidth/5*4,display.contentHeight/5*4 )
img2.x = display.contentWidth/2
img2.y = display.contentHeight/2
grp2:insert(rct2)
grp2:insert(img2)
grp2:insert(txt2)
myFirstFlipbook:addPage( grp1 )
myFirstFlipbook:addMirror( nrPages, grp2 )
end
And flipbook.lua file:
-----------------------------------------------------------------------------------------
--
-- flipbook.lua
--
-----------------------------------------------------------------------------------------
local Flipbook = {
mask = graphics.newMask( "mask1.png" ),
mask2 = graphics.newMask( "mask2.png" ),
currentPage = 1,
pages = {},
backPages = {},
displayGroup = display.newGroup(),
control = 2
}
Flipbook.__index = Flipbook
function Flipbook:newFlipbook(nrPages, newBackShadow, newBasicShadow, newCurlShadow) --Create a new flipbook
local tempFlipbook = setmetatable({},self)
-- Adds a shadow for where the curled page overlaps itself
tempFlipbook.backShadow = display.newImage( newBackShadow )
tempFlipbook.backShadow.isHitTestMasked = false
tempFlipbook.backShadow.y = display.contentHeight / 2
tempFlipbook.backShadow.isVisible = false
tempFlipbook.displayGroup:insert( nrPages + 1, tempFlipbook.backShadow )
-- Adds event listener
tempFlipbook.displayGroup:addEventListener( "touch", tempFlipbook )
----
return tempFlipbook
end
function Flipbook:addPage( newPageGroup ) -- Add a new page to your flipbook
local tempPageImage = newPageGroup
tempPageImage:setMask( self.mask )
tempPageImage.maskX = display.contentWidth
tempPageImage.isHitTestMasked = false
tempPageImage:setReferencePoint( display.CenterReferencePoint )
table.insert( self.pages, tempPageImage ) -- Adds new page to pages index
self.displayGroup:insert( 1, tempPageImage ) -- Adds new page to display group
end
function Flipbook:addMirror( nrPages, newPageGroup )
local tempPageImageMirror = newPageGroup
tempPageImageMirror.isVisible = false
tempPageImageMirror:setMask( self.mask2 )
tempPageImageMirror:setReferencePoint( display.CenterReferencePoint )
table.insert( self.backPages, tempPageImageMirror ) -- Adds new page to pages index
self.displayGroup:insert( nrPages + 1, tempPageImageMirror )
end
function Flipbook:updateCurlEffect( handleX, handleY, originY ) -- Updates the curl effect assets
local hX = 0
if (handleX > display.contentWidth) then
hX = display.contentWidth
elseif (handleX < 0) then
hX = 0
else
hX = handleX
end
local controlX = 0
if (hX > display.contentWidth / 2) then
controlX = (( hX - display.contentWidth / 2) / (display.contentWidth / 2))
else
controlX = (( display.contentWidth / 2 - hX ) / (display.contentWidth / 2))
end
if controlX < 0.0001 then
controlX = 0.0001
end
if controlX > 0.9999 then
controlX = 0.9999
end
--print(alphaX)
self.pages[self.currentPage].maskX = hX
if (hX > display.contentWidth / 2) then
self.backPages[self.currentPage+1].isVisible = false
self.backPages[self.currentPage]:setMask(self.mask2)
self.backPages[self.currentPage].isVisible = true
self.backPages[self.currentPage].xReference = 0
self.backPages[self.currentPage].x = (display.contentWidth - hX)
self.backPages[self.currentPage].maskX = display.contentWidth / 2
self.backPages[self.currentPage].xScale = controlX
if (self.control > 1) then
self.backShadow:scale(-1,1)
self.control = 1
--self.backShadow.xReference = display.contentWidth / 2
self.backShadow.x = display.contentWidth + 21
self.backShadow.maskX = 0
end
else
self.backPages[self.currentPage].isVisible = false
self.backPages[self.currentPage+1].isVisible = true
self.backPages[self.currentPage+1]:setMask(self.mask)
self.backPages[self.currentPage+1]:toFront()
self.backPages[self.currentPage+1].xReference = 0
self.backPages[self.currentPage+1].x = hX
self.backPages[self.currentPage+1].maskX = display.contentWidth / 2
self.backPages[self.currentPage+1].xScale = controlX
if (self.control < 2) then
self.backShadow:scale(-1,1)
self.control = 2
--self.backShadow.xReference = display.contentWidth / 2
self.backShadow.x = -21
self.backShadow.maskX = 0
end
end
self.backShadow.alpha = controlX
--self.backShadow.sizeX = display.contentWidth
end
function Flipbook:setAssetsVisible( isVisibleBoolean ) -- Curl effect assets visibility switch box
if isVisibleBoolean then
self.backPages[self.currentPage].isVisible = isVisibleBoolean
self.backShadow.isVisible = isVisibleBoolean
self.backShadow:toFront()
self.backPages[self.currentPage]:toFront()
else
--for k,v in pairs(self.backPages) do
for k=1, #self.backPages do
self.backPages[k].isVisible = isVisibleBoolean
end
self.backShadow.isVisible = isVisibleBoolean
end
end
function Flipbook:touch( event )
if event.phase == "began" then
if event.xStart > 5 * display.contentWidth / 6 and self.currentPage < # self.pages
or event.xStart < display.contentWidth / 6 and self.currentPage > 1 then
if event.xStart < display.contentWidth / 6 then
self.currentPage = self.currentPage - 1
self.pages[self.currentPage].isVisible = true
end
display.getCurrentStage():setFocus( self.displayGroup )
self.isFocus = true
self:setAssetsVisible( true )
else
return false
end
end
if self.isFocus then
self:updateCurlEffect( event.x, event.y, event.yStart )
if event.phase == "ended" or event.phase == "cancelled" then
self:updateCurlEffect( display.contentWidth, 0, 0 )
if math.abs(event.x - event.xStart) > display.contentWidth / 6 then
if event.xStart > 5 * display.contentWidth / 6 and self.currentPage < # self.pages then
self.pages[self.currentPage].isVisible = false
self.currentPage = self.currentPage + 1
end
self:setAssetsVisible( false )
display.getCurrentStage():setFocus( nil )
self.isFocus = nil
else
if event.xStart < display.contentWidth / 6 and self.currentPage > 1 then
self.pages[self.currentPage].isVisible = false
self.currentPage = self.currentPage + 1
end
self:setAssetsVisible( false )
display.getCurrentStage():setFocus( nil )
self.isFocus = nil
end
end
return true
end
end
return Flipbook
For the files backgroundX.png I used the files from FLIPBOOK project.
And for the mainshadow2.jpg, I used a hole black image with a 75% alpha, based on the mainshadow.jpg size from the FLIPBOOK project.
Hope it helps.
Best regards.
Alexandre Flores de Almeida
It's already answered. It's not a question, but code for the community.

CORONA: How to vanish an object on touch or tap?

I have objects like stone and apple falling continuously, now I need to vanish the apple on touch and get count of apples I touch.... pls help... I'm totally new to CORONA....
here is my code:
function newApples()
rand = math.random( 100 )
if (rand < 60) then
j = display.newImage("s1.png");
j.x = 60 + math.random( 160 )
j.y = -100
physics.addBody( j, { density=0.9, friction=0.3, bounce=0.3} )
elseif (rand < 80) then
j = display.newImage("s2.png");
j.x = 60 + math.random( 160 )
j.y = -100
physics.addBody( j, { density=1.4, friction=0.3, bounce=0.2} )
else
apple = display.newImage("apple1.png");
apple.x = 60 + math.random( 160 )
apple.y = -100
physics.addBody( apple, { density=0.3, friction=0.2, bounce=0.5} )
apple.name = "apple"
end
end
local dropApples = timer.performWithDelay( 500, newApples, -1 )
function onTouch(event)
print("this")
event:removeSelf()
end
apple:addEventListener("tap",onTouch)
I think this code help you:
local physics = require("physics")
physics.start()
local appletouchcount=0
function newApples()
rand = math.random( 100 )
if (rand < 60) then
j = display.newImage("s1.png");
j.x = 60 + math.random( 160 )
j.y = -100
elseif (rand < 80) then
j = display.newImage("s2.png");
j.x = 60 + math.random( 160 )
j.y = -100
physics.addBody( j, { density=1.4, friction=0.3, bounce=0.2} )
else
apple = display.newImage("apple1.png");
apple.x = 60 + math.random( 160 )
apple.y = -100
physics.addBody( apple, { density=0.3, friction=0.2, bounce=0.5} )
apple.name = "apple"
function onTouch(event)
appletouchcount= appletouchcount+1
print("this")
event.target:removeSelf()
print("total"..appletouchcount)
end
apple:addEventListener("touch",onTouch)
end
end
local dropApples = timer.performWithDelay( 500, newApples, -1 )
appletouchcount is a count of apple you touched.
use new-text to show ur count where u want:
local physics = require("physics")
physics.start()
local appletouchcount=0
local text = display.newText("Total ", 0, 0, native.systemFont, 16)
text.x=150;text.y=50
function newApples()
rand = math.random( 100 )
if (rand < 60) then
j = display.newImage("s1.png");
j.x = 60 + math.random( 160 )
j.y = -100
elseif (rand < 80) then
j = display.newImage("s2.png");
j.x = 60 + math.random( 160 )
j.y = -100
physics.addBody( j, { density=1.4, friction=0.3, bounce=0.2} )
else
apple = display.newImage("apple1.png");
apple.x = 60 + math.random( 160 )
apple.y = -100
physics.addBody( apple, { density=0.3, friction=0.2, bounce=0.5} )
apple.name = "apple"
function onTouch(event)
if event.phase=="ended" then
text.text="Total "..appletouchcount
appletouchcount= appletouchcount+1
print("this")
event.target:removeSelf()
print("total"..appletouchcount)
end
print(appletouchcount)
end
apple:addEventListener("touch",onTouch)
end
end
local dropApples = timer.performWithDelay( 500, newApples, -1 )
Before i want to say one thing i.e remove unnecessary object it cause the memory problem make the app slow .But even though lua language have memory management.
I think below code reach your exception
local physics = require("physics")
physics.start()
local appletouchcount=0;local count={total1=0,total=0,touch=0,loss=0}
local total=display.newText("Total:0 \n AppleTotal:0 \n AppleGot:0 \n AppleLoss:0",display.contentCenterX*0.25, 60, native.systemFont, 26)
local collisionListener=function(self,event)
print(event.other.type)
if(event.phase=="began")then
if(event.other.type=="apple")then
count.loss=count.loss+1
event.other:removeSelf();event.other=nil
else
event.other:removeSelf();event.other=nil
end
end
end
function newApples(event)
count.total1=event.count
total.text="Total:"..count.total1.." \n AppleTotal:"..count.total.." \n AppleGot:"..count.touch.." \n AppleLoss:"..count.loss
rand = math.random( 100 )
if (rand < 60) then
j = display.newCircle(0,0,40)--display.newImage("s1.png");
j.x = 60 + math.random( 160 )
j.y = -100
j.type="other"
physics.addBody( j, { density=1.4, friction=0.3, bounce=0.2} )
elseif (rand < 80) then
j = display.newCircle(0,0,40)--display.newImage("s2.png");
j.x = 60 + math.random( 160 )
j.y = -100
j.type="other"
physics.addBody( j, { density=1.4, friction=0.3, bounce=0.2} )
else
apple =display.newCircle(0,0,70) --display.newImage("apple1.png");
apple.x = 60 + math.random( 160 )
apple.y = -100
apple.type="apple"
apple:setFillColor(255,0,0)
count.total= count.total+1
physics.addBody( apple, { density=0.3, friction=0.2, bounce=0.5} )
apple.name = "apple"
function onTouch(event)
count.touch=count.touch+1
total.text="Total:"..count.total1.." \n AppleTotal:"..count.total.." \n AppleGot:"..count.touch.." \n AppleLoss:"..count.loss
event.target:removeSelf()
print("total"..appletouchcount)
end
apple:addEventListener("touch",onTouch)
end
end
botwall=display.newRect(0,display.contentHeight,display.contentWidth,10)
botwall:setFillColor(22,125,185,255)
botwall.type="botwall"
botwall.collision=collisionListener
physics.addBody(botwall,"static",{ density=100.0, friction=0.0, bounce=0.0} )
botwall:addEventListener("collision",botwall)
local dropApples = timer.performWithDelay( 500, newApples, -1 )
To make something invisible you just set its alpha to 0. This makes it 100% transparent.
apple.alpha = 0;
Docs: http://docs.coronalabs.com/api/type/DisplayObject/alpha.html

Corona SDK: Remove display object from table

I have been working on a tower defense game. So basically I have a loop that makes a table of display objects that are tanks and adds physics bodies to them. Then it "gives the tanks" to a function called moveTank to actually move them.
However to conserve memory I want to remove the physics body and display obejct itself once it is offscreen. The code for that stars at line 234. In the simulator, if you test just removing the physics body everything works fine. However, if I remove the display object (maybe I'm doing it wrong?) it removes the image, but some other functions that use it give an error saying that I'm trying to compare a number with a nil value# line 229. The nil value is the object is removed and I set its property isMoving and isAlive to false so why is it even trying to perform the operation??
Can anyone help me finish this part of trying to remove the display object with no errors?
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local physics = require "physics"
physics.start()
physics.setGravity( 0, 0)
physics.setDrawMode("hybrid")
local screenW, screenH, halfW, halfH = display.contentWidth, display.contentHeight, display.contentWidth*0.5, display.contentHeight*0.5
local tanks = {}
local tickCnt = 0
local TOTAL_TANKS = 2
local tankCnt = 1
function AddCommas( number, maxPos )
local s = tostring( number )
local len = string.len( s )
if len > maxPos then
-- Add comma to the string
local s2 = string.sub( s, -maxPos )
local s1 = string.sub( s, 1, len - maxPos )
s = (s1 .. "," .. s2)
end
maxPos = maxPos - 3 -- next comma position
if maxPos > 0 then
return AddCommas( s, maxPos )
else
return s
end
end
function tickCntFunct()
if tickCnt <= 2000 then
tickCnt = tickCnt + 25
print("tick count", tickCnt)
else
tickCnt = 0
end
end
timer.performWithDelay(10, tickCntFunct, 0)
function moveTank(aTank)
local mSpeed = 150
rSpeed = 6
if aTank.isAlive == true and aTank.isKilled == false then
print("aTank.x = ", aTank.x)
print("aTank.y = ", aTank.y)
print("tank rotation = ", aTank.rotation)
local disP1 = math.sqrt((math.abs(aTank.x - pointer1.x))^2 + (math.abs(aTank.y - pointer1.y))^2)
local disP2 = math.sqrt((math.abs(aTank.x - pointer2.x))^2 + (math.abs(aTank.y - pointer2.y))^2)
local disP3 = math.sqrt((math.abs(aTank.x - pointer3.x))^2 + (math.abs(aTank.y - pointer3.y))^2)
local disP4 = math.sqrt((math.abs(aTank.x - pointer4.x))^2 + (math.abs(aTank.y - pointer4.y))^2)
removeTanknumber = 0
if aTank.x < 0 then
aTank.rotation = 90
aTank:setLinearVelocity( mSpeed, 0)
end
if aTank.rotation < 180 and disP1 < 1 then
aTank:setLinearVelocity( 0, 0)
aTank.rotation = aTank.rotation + rSpeed
end
if aTank.rotation >= 180 and disP1 < 1 then
aTank.rotation = 180
aTank:setLinearVelocity( 0, mSpeed)
end
if aTank.rotation > 90 and disP2 < 1 then
aTank:setLinearVelocity( 0, 0)
aTank.rotation = aTank.rotation - rSpeed
end
if aTank.rotation <= 90 and disP2 < 1 then
aTank.rotation = 90
aTank:setLinearVelocity( mSpeed, 0)
end
if aTank.rotation > 0 and disP3 < 1 then
aTank:setLinearVelocity( 0, 0)
aTank.rotation = aTank.rotation - rSpeed
end
if aTank.rotation <= 0 and disP3 < 1 then
aTank.rotation = 0
aTank:setLinearVelocity( 0, -1*mSpeed)
end
if aTank.rotation < 90 and disP4 < 1 then
aTank:setLinearVelocity( 0, 0)
aTank.rotation = aTank.rotation + rSpeed
end
if aTank.rotation >= 90 and disP4 < 1 then
aTank.rotation = 90
aTank:setLinearVelocity( mSpeed, 0)
end
end
end
timer.performWithDelay(1, moveTank, 0)
function scene:createScene( event )
local group = self.view
pointersGroup = display.newGroup()
mapGroup = display.newGroup()
-- create a grey rectangle as the backdrop
map = display.newImage( "map1.png" )
map:setReferencePoint(display.TopLeftReferencePoint)
map.x = 0
map.y = 0
spawner = display.newImage("pointer.png")
spawner:setReferencePoint(display.CenterReferencePoint)
spawner.y = 210
spawner.x = -40
pointer1 = display.newImage("pointer.png")
pointer1:setReferencePoint(display.CenterReferencePoint)
pointer1.x = 210
pointer1.y = 210
pointer2 = display.newImage("pointer.png")
pointer2:setReferencePoint(display.CenterReferencePoint)
pointer2.x = 210
pointer2.y = 390
pointer3 = display.newImage("pointer.png")
pointer3:setReferencePoint(display.CenterReferencePoint)
pointer3.x = 510
pointer3.y = 390
pointer4 = display.newImage("pointer.png")
pointer4:setReferencePoint(display.CenterReferencePoint)
pointer4.x = 510
pointer4.y = 90
sideBlock = display.newImage("side_block.png")
physics.addBody( sideBlock, "static", { friction=0.5, bounce=0.3 } )
sideBlock:setReferencePoint(display.CenterReferencePoint)
sideBlock.x = screenW - 100
sideBlock.y = screenH/2
-- all display objects must be inserted into group
pointersGroup:insert( spawner )
pointersGroup:insert( pointer1 )
pointersGroup:insert( pointer2 )
pointersGroup:insert( pointer3 )
pointersGroup:insert( pointer4 )
pointersGroup:insert( sideBlock )
mapGroup:insert( map )
group:insert( pointersGroup )
group:insert( mapGroup )
end
function scene:enterScene( event )
local group = self.view
for i = 1, TOTAL_TANKS do
-- create 5 tanks, place them off screen, set their status to isAlive and not isMoving
table.insert(tanks, display.newImage("tank.png"))
print("memory (all spawned): ", AddCommas( system.getInfo("textureMemoryUsed"), 9 ) .. " bytes" )
tanks[i]:setReferencePoint(display.CenterReferencePoint)
tanks[i]:scale(0.75, 0.75)
tanks[i].x = spawner.x
tanks[i].y = spawner.y
tanks[i].isAlive = true
tanks[i].isMoving = false
tanks[i].isKilled = false
end
local function gameLoop(event)
-- normally should not have loops inside the game loop, because
-- if there is too much going on during each frame call it can cause issues
-- but for moving only 5 tanks, this is how you can do it.
-- each tank will call the same function above (moveTank)
-- have a variable that you would check here, to see if 'so many ticks or seconds'
-- has passed, and if so, set the isMoving to true for the next tank .. will just use
-- a simple incremented variable 'tickCnt'
if tickCnt > 2000 and tankCnt <= TOTAL_TANKS then
physics.addBody( tanks[tankCnt], { density=3.0, friction=0.5, bounce=0.3 } )
tanks[tankCnt].isMoving = true
print("tankCnt= ", tankCnt)
tankCnt = tankCnt + 1
print("memory (moving): ", AddCommas( system.getInfo("textureMemoryUsed"), 9 ) .. " bytes" )
end
for i=1, TOTAL_TANKS do
if tanks[i].isMoving == true and tanks[i].isAlive == true and tanks[i].isKilled == false then
moveTank(tanks[i])
end
end
for i = 1, TOTAL_TANKS do
if tanks[i].x >= 40 and tanks[i].isKilled == false then
tanks[i].isKilled = true
tanks[i].isMoving = false
tanks[i].isAlive = false
physics.removeBody( tanks[i] )
display.remove(tanks[i])
tanks[i] = nil
end
end
end
Runtime:addEventListener("enterFrame", gameLoop)
physics.start()
end
function scene:exitScene( event )
local group = self.view
physics.stop()
end
function scene:destroyScene( event )
local group = self.view
package.loaded[physics] = nil
physics = nil
end
--------------------------------------------------------------------------------------- --
-- END OF YOUR IMPLEMENTATION
-----------------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched whenever before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
-----------------------------------------------------------------------------------------
return scene
Try to loop from last tank to first.

Resources