I am having a strange issue with Corona SDK. I have an egg style catching game where you collect items and avoid certain objects. The player is moved left and right with an accelerometer and objects fall from the sky. The game runs well, except for a major flaw: when the dangerous objects hit the initial player's location (where the player is spawned - x = 160, y = display.contentHeight - 40), collision is detected among the player and the object. As a result there is a ghost effect happening when objects drop to x = 160 (+ or - the width of the player / 2).
The player object:
local createChar = function()
charObject = display.newImageRect( "charSprite.png", y/9, y/9 )
physics.addBody( charObject, "static", { density=1.0, bounce=0.4, friction=0.15, radius=20, shape=basketShape} )
charObject.x = -100; charObject.y = y - ground.contentHeight - y/22
charObject.rotation = 0
charObject.isHit = false
charObject.myName = "character"
fishDead = display.newImageRect( "fishdead.png", y/20, y/20 )
fishDead.alpha = 1.0
fishDead.isVisible = false
gameGroup:insert( charObject )
end
The dangerous sea lion object is created through a timer (every 3 seconds). This is the code for each time interval
local sealionDrop = function()
if gameIsActive == true then
local sealion = display.newImageRect( "sealion.png", y / 11, y / 11 )
sealion.x = 40 + mRand( x - 55 ); sealion.y = -100
sealion.isHit = false
physics.addBody( sealion, "dynamic",{ density=20, bounce=0, friction=1, shape=sealionShape } )
sealion.isFixedRotation = true
gameGroup:insert( sealion )
sealion.gravityScale = sealionSpeed
sealion.postCollision = onLionCollision
sealion:addEventListener( "postCollision", sealion )
end
end
Here is my collision code between the player and the dangerous "sealion" object:
local onLionCollision = function( self, event )
if event.other.myName == "character" and charObject.x == self.x then
hit = timer.performWithDelay( 1, characterHit, 2 )
livesCount()
self.isHit = true
self.parent:remove( self )
self = nil
elseif event.other.myName == "ground" then
print("ground hit")
self.isHit = true
self.parent:remove( self )
self = nil
end
if gameLives < 1 then
timer.cancel( startLionDrop )
print("timer cancelled")
end
end
If someone could help figure out this weird ghost effect, that would be amazing. Thank you!
i just have a quick question. Im playing around with Corona to try and get the look and feel of it and im currently editing some one else's sample code. I have added a scoring mechanism, and now i want to add a combo scoring mechanism so that when the user chops more than one fruit, i can add an extra 5 points. Its just that i have no idea how to start. If some one would point me in the right direction that would be great thank you. :)
Or if this would be much clearer: How about a function that will help me detect how many objects the user touches/slices in one touch/move?
require ("physics")
local ui = require("ui")
physics.start()
-- physics.setDrawMode ( "hybrid" ) -- Uncomment in order to show in hybrid mode
physics.setGravity( 0, 9.8 * 2)
physics.start()
-- Audio for slash sound (sound you hear when user swipes his/her finger across the screen)
local slashSounds = {slash1 = audio.loadSound("slash1.wav"), slash2 = audio.loadSound("slash2.wav"), slash3 = audio.loadSound("slash3.wav")}
local slashSoundEnabled = true -- sound should be enabled by default on startup
local minTimeBetweenSlashes = 150 -- Minimum amount of time in between each slash sound
local minDistanceForSlashSound = 50 -- Amount of pixels the users finger needs to travel in one frame in order to play a slash sound
-- Audio for chopped fruit
local choppedSound = {chopped1 = audio.loadSound("chopped1.wav"), chopped2 = audio.loadSound("chopped2.wav")}
-- Audio for bomb
local preExplosion = audio.loadSound("preExplosion.wav")
local explosion = audio.loadSound("explosion.wav")
-- Adding a collision filter so the fruits do not collide with each other, they only collide with the catch platform
local fruitProp = {density = 1.0, friction = 0.3, bounce = 0.2, filter = {categoryBits = 2, maskBits = 1}}
local catchPlatformProp = {density = 1.0, friction = 0.3, bounce = 0.2, filter = {categoryBits = 1, maskBits = 2}}
-- Gush filter should not interact with other fruit or the catch platform
local gushProp = {density = 1.0, friction = 0.3, bounce = 0.2, filter = {categoryBits = 4, maskBits = 8} }
-- Will contain all fruits available in the game
local avalFruit = {}
-- Slash line properties (line that shows up when you move finger across the screen)
local maxPoints = 5
local lineThickness = 20
local lineFadeTime = 250
local endPoints = {}
-- Whole Fruit physics properties
local minVelocityY = 850
local maxVelocityY = 1100
local minVelocityX = -200
local maxVelocityX = 200
local minAngularVelocity = 100
local maxAngularVelocity = 200
-- Chopped fruit physics properties
local minAngularVelocityChopped = 100
local maxAngularVelocityChopped = 200
-- Splash properties
local splashFadeTime = 2500
local splashFadeDelayTime = 5000
local splashInitAlpha = .5
local splashSlideDistance = 50 -- The amoutn of of distance the splash slides down the background
-- Contains all the available splash images
local splashImgs = {}
-- Gush properties
local minGushRadius = 10
local maxGushRadius = 25
local numOfGushParticles = 15
local gushFadeTime = 500
local gushFadeDelay = 500
local minGushVelocityX = -350
local maxGushVelocityX = 350
local minGushVelocityY = -350
local maxGushVelocityY = 350
-- Timer references
local bombTimer
local fruitTimer
-- Game properties
local fruitShootingInterval = 1000
local bombShootingInterval = 5000
-- Groups for holding the fruit and splash objects
local splashGroup
local fruitGroup
local sampleVar = true
local score = 0
local scoreText
function main()
score = 0
display.setStatusBar( display.HiddenStatusBar )
setUpBackground()
scoreText = display.newText("Score: 0", 415, 100, native.systemFont, 50)
scoreText:setTextColor(255, 255, 255)
scoreText.text = ("Score: " )..score
pauseAndResume ()
setUpCatchPlatform()
initGroups()
initFruitAndSplash()
Runtime:addEventListener("touch", drawSlashLine)
timer.performWithDelay( 1000, displayScore)
startGame()
end
function displayScore()
scoreText.text = ("Score: " )..score
score = score + 2
end
function startGame()
shootObject("fruit")
bombTimer = timer.performWithDelay(bombShootingInterval, function(event) shootObject("bomb") end, 0)
fruitTimer = timer.performWithDelay(fruitShootingInterval, function(event) shootObject("fruit") end, 0)
end
-- Display the pause button
function pauseAndResume ()
pausebutton = display.newImage ("paused2.png", 10, 100)
pausebutton:addEventListener ("touch" , pauseGame)
resumebutton = display.newImage ("resume.png", 10, 100)
resumebutton.isVisible = false
resumebutton:addEventListener ("touch", resumeGame)
end
function pauseGame (event)
if (event.phase == "ended") then
physics.pause ()
pausebutton.isVisible = false
resumebutton.isVisible = true
timer.pause(fruitTimer)
timer.pause(bombTimer)
sampleVar = false
return true
end
end
function resumeGame (event)
if (event.phase == "ended") then
physics.start()
pausebutton.isVisible = true
resumebutton.isVisible = false
timer.resume(fruitTimer)
timer.resume(bombTimer)
sampleVar = true
return true
end
end
function initGroups()
splashGroup = display.newGroup()
fruitGroup = display.newGroup()
end
function setUpBackground()
local background = display.newImage("bg.png", true)
background.x = display.contentWidth / 2
background.y = display.contentHeight / 2
end
-- Populates avalFruit with all the fruit images and thier widths and heights
function initFruitAndSplash()
local watermelon = {}
watermelon.whole = "watermelonWhole.png"
watermelon.top = "watermelonTop.png"
watermelon.bottom = "watermelonBottom.png"
watermelon.splash = "redSplash.png"
table.insert(avalFruit, watermelon)
local strawberry = {}
strawberry.whole = "strawberryWhole.png"
strawberry.top = "strawberryTop.png"
strawberry.bottom = "strawberryBottom.png"
strawberry.splash = "redSplash.png"
table.insert(avalFruit, strawberry)
-- Initialize splash images
table.insert(splashImgs, "splash1.png")
table.insert(splashImgs, "splash2.png")
table.insert(splashImgs, "splash3.png")
end
function getRandomFruit()
local fruitProp = avalFruit[math.random(1, #avalFruit)]
local fruit = display.newImage(fruitProp.whole)
fruit.whole = fruitProp.whole
fruit.top = fruitProp.top
fruit.bottom = fruitProp.bottom
fruit.splash = fruitProp.splash
return fruit
end
function getBomb()
local bomb = display.newImage( "bomb.png")
return bomb
end
function shootObject(type)
local object = type == "fruit" and getRandomFruit() or getBomb()
fruitGroup:insert(object)
object.x = display.contentWidth / 2
object.y = display.contentHeight + object.height * 2
fruitProp.radius = object.height / 2
physics.addBody(object, "dynamic", fruitProp)
if(type == "fruit") then
object:addEventListener("touch", function(event) chopFruit(object) end)
else
local bombTouchFunction
bombTouchFunction = function(event) explodeBomb(object, bombTouchFunction); end
object:addEventListener("touch", bombTouchFunction)
end
-- Apply linear velocity
local yVelocity = getRandomValue(minVelocityY, maxVelocityY) * -1 -- Need to multiply by -1 so the fruit shoots up
local xVelocity = getRandomValue(minVelocityX, maxVelocityX)
object:setLinearVelocity(xVelocity, yVelocity)
-- Apply angular velocity (the speed and direction the fruit rotates)
local minAngularVelocity = getRandomValue(minAngularVelocity, maxAngularVelocity)
local direction = (math.random() < .5) and -1 or 1
minAngularVelocity = minAngularVelocity * direction
object.angularVelocity = minAngularVelocity
end
function explodeBomb(bomb, listener)
bomb:removeEventListener("touch", listener)
-- The bomb should not move while exploding
bomb.bodyType = "kinematic"
bomb:setLinearVelocity(0, 0)
bomb.angularVelocity = 0
-- Shake the stage
local stage = display.getCurrentStage()
local moveRightFunction
local moveLeftFunction
local rightTrans
local leftTrans
local shakeTime = 50
local shakeRange = {min = 1, max = 25}
moveRightFunction = function(event) rightTrans = transition.to(stage, {x = math.random(shakeRange.min,shakeRange.max), y = math.random(shakeRange.min, shakeRange.max), time = shakeTime, onComplete=moveLeftFunction}); end
moveLeftFunction = function(event) leftTrans = transition.to(stage, {x = math.random(shakeRange.min,shakeRange.max) * -1, y = math.random(shakeRange.min,shakeRange.max) * -1, time = shakeTime, onComplete=moveRightFunction}); end
moveRightFunction()
local linesGroup = display.newGroup()
-- Generate a bunch of lines to simulate an explosion
local drawLine = function(event)
local line = display.newLine(bomb.x, bomb.y, display.contentWidth * 2, display.contentHeight * 2)
line.rotation = math.random(1,360)
line.width = math.random(15, 25)
linesGroup:insert(line)
end
local lineTimer = timer.performWithDelay(100, drawLine, 0)
-- Function that is called after the pre explosion
local explode = function(event)
audio.play(explosion)
blankOutScreen(bomb, linesGroup);
timer.cancel(lineTimer)
stage.x = 0
stage.y = 0
transition.cancel(leftTrans)
transition.cancel(rightTrans)
end
-- Play the preExplosion sound first followed by the end explosion
audio.play(preExplosion, {onComplete = explode})
timer.cancel(fruitTimer)
timer.cancel(bombTimer)
end
function blankOutScreen(bomb, linesGroup)
local gameOver = displayGameOver()
gameOver.alpha = 0 -- Will reveal the game over screen after the explosion
-- Create an explosion animation
local circle = display.newCircle( bomb.x, bomb.y, 5 )
local circleGrowthTime = 300
local dissolveDuration = 1000
local dissolve = function(event) transition.to(circle, {alpha = 0, time = dissolveDuration, delay = 0, onComplete=function(event) gameOver.alpha = 1 end}); gameOver.alpha = 1 end
circle.alpha = 0
transition.to(circle, {time=circleGrowthTime, alpha = 1, width = display.contentWidth * 3, height = display.contentWidth * 3, onComplete = dissolve})
end
function displayGameOver()
-- Will return a group so that we can set the alpha of the entier menu
local group = display.newGroup()
-- Dim the background with a transperent square
local back = display.newRect( 0,0, display.contentWidth, display.contentHeight )
back:setFillColor(0,0,0, 255 * .1)
group:insert(back)
local gameOver = display.newImage( "gameover.png")
gameOver.x = display.contentWidth / 2
gameOver.y = display.contentHeight / 2
group:insert(gameOver)
local replayButton = ui.newButton{
default = "replayButton.png",
over = "replayButton.png",
onRelease = function(event) group:removeSelf(); main() ; end
}
group:insert(replayButton)
replayButton.x = display.contentWidth / 2
replayButton.y = gameOver.y + gameOver.height / 2 + replayButton.height / 2
return group
end
-- Return a random value between 'min' and 'max'
function getRandomValue(min, max)
return min + math.abs(((max - min) * math.random()))
end
function playRandomSlashSound()
audio.play(slashSounds["slash" .. math.random(1, 3)])
end
function playRandomChoppedSound()
audio.play(choppedSound["chopped" .. math.random(1, 2)])
end
function getRandomSplash()
return display.newImage(splashImgs[math.random(1, #splashImgs)])
end
function chopFruit(fruit)
if (sampleVar == true) then
displayScore()
playRandomChoppedSound()
createFruitPiece(fruit, "top")
createFruitPiece(fruit, "bottom")
createSplash(fruit)
createGush(fruit)
fruit:removeSelf()
end
end
-- Creates a gushing effect that makes it look like juice is flying out of the fruit
function createGush(fruit)
local i
for i = 0, numOfGushParticles do
local gush = display.newCircle( fruit.x, fruit.y, math.random(minGushRadius, maxGushRadius) )
gush:setFillColor(255, 0, 0, 255)
gushProp.radius = gush.width / 2
physics.addBody(gush, "dynamic", gushProp)
local xVelocity = math.random(minGushVelocityX, maxGushVelocityX)
local yVelocity = math.random(minGushVelocityY, maxGushVelocityY)
gush:setLinearVelocity(xVelocity, yVelocity)
transition.to(gush, {time = gushFadeTime, delay = gushFadeDelay, width = 0, height = 0, alpha = 0, onComplete = function(event) gush:removeSelf() end})
end
end
function createSplash(fruit)
local splash = getRandomSplash()
splash.x = fruit.x
splash.y = fruit.y
splash.rotation = math.random(-90,90)
splash.alpha = splashInitAlpha
splashGroup:insert(splash)
transition.to(splash, {time = splashFadeTime, alpha = 0, y = splash.y + splashSlideDistance, delay = splashFadeDelayTime, onComplete = function(event) splash:removeSelf() end})
end
-- Chops the fruit in half
-- Uses some trig to calculate the position
-- of the top and bottom part of the chopped fruit (http://en.wikipedia.org/wiki/Rotation_matrix#Rotations_in_two_dimensions)
function createFruitPiece(fruit, section)
local fruitVelX, fruitVelY = fruit:getLinearVelocity()
-- Calculate the position of the chopped piece
local half = display.newImage(fruit[section])
half.x = fruit.x - fruit.x -- Need to have the fruit's position relative to the origin in order to use the rotation matrix
local yOffSet = section == "top" and -half.height / 2 or half.height / 2
half.y = fruit.y + yOffSet - fruit.y
local newPoint = {}
newPoint.x = half.x * math.cos(fruit.rotation * (math.pi / 180)) - half.y * math.sin(fruit.rotation * (math.pi / 180))
newPoint.y = half.x * math.sin(fruit.rotation * (math.pi / 180)) + half.y * math.cos(fruit.rotation * (math.pi / 180))
half.x = newPoint.x + fruit.x -- Put the fruit back in its original position after applying the rotation matrix
half.y = newPoint.y + fruit.y
fruitGroup:insert(half)
-- Set the rotation
half.rotation = fruit.rotation
fruitProp.radius = half.width / 2 -- We won't use a custom shape since the chopped up fruit doesn't interact with the player
physics.addBody(half, "dynamic", fruitProp)
-- Set the linear velocity
local velocity = math.sqrt(math.pow(fruitVelX, 2) + math.pow(fruitVelY, 2))
local xDirection = section == "top" and -1 or 1
local velocityX = math.cos((fruit.rotation + 90) * (math.pi / 180)) * velocity * xDirection
local velocityY = math.sin((fruit.rotation + 90) * (math.pi / 180)) * velocity
half:setLinearVelocity(velocityX, velocityY)
-- Calculate its angular velocity
local minAngularVelocity = getRandomValue(minAngularVelocityChopped, maxAngularVelocityChopped)
local direction = (math.random() < .5) and -1 or 1
half.angularVelocity = minAngularVelocity * direction
end
-- Creates a platform at the bottom of the game "catch" the fruit and remove it
function setUpCatchPlatform()
local platform = display.newRect( 0, 0, display.contentWidth * 4, 50)
platform.x = (display.contentWidth / 2)
platform.y = display.contentHeight + display.contentHeight
physics.addBody(platform, "static", catchPlatformProp)
platform.collision = onCatchPlatformCollision
platform:addEventListener( "collision", platform )
end
function onCatchPlatformCollision(self, event)
-- Remove the fruit that collided with the platform
event.other:removeSelf()
end
-- Draws the slash line that appears when the user swipes his/her finger across the screen
function drawSlashLine(event)
-- Play a slash sound
if(endPoints ~= nil and endPoints[1] ~= nil) then
local distance = math.sqrt(math.pow(event.x - endPoints[1].x, 2) + math.pow(event.y - endPoints[1].y, 2))
if(distance > minDistanceForSlashSound and slashSoundEnabled == true) then
playRandomSlashSound();
slashSoundEnabled = false
timer.performWithDelay(minTimeBetweenSlashes, function(event) slashSoundEnabled = true end)
end
end
-- Insert a new point into the front of the array
table.insert(endPoints, 1, {x = event.x, y = event.y, line= nil})
-- Remove any excessed points
if(#endPoints > maxPoints) then
table.remove(endPoints)
end
for i,v in ipairs(endPoints) do
local line = display.newLine(v.x, v.y, event.x, event.y)
line.width = lineThickness
transition.to(line, {time = lineFadeTime, alpha = 0, width = 0, onComplete = function(event) line:removeSelf() end})
end
if(event.phase == "ended") then
while(#endPoints > 0) do
table.remove(endPoints)
end
end
end
main()
Try Runtime touch listener ...in that listener event.phase == "move" you can do like above.In event.phase=="ended" reset the value.
Initial set some temp value.
Tempvalue=0
function displayScore()
if Tempvalue == 0 then
Tempvalue=Tempvalue+1
score = score + 2
scoreText.text = ("Score: " )..score
else
score = score + 5
scoreText.text = ("Score: " )..score
end
I just put the sample how to do.
temp=0
local newLine = function(event)
if event.phase=="began" then
elseif event.phase=="moved" then
for i=1,3 do
if event.target.name==i then
temp=temp+1
--here you can do your action to the object(like remove or score)
print("touch"..temp)
end
end
elseif event.phase=="ended" then
end
return true
end
for i=1,3 do
local myCircle = display.newCircle( 100*i, 100, 9 )
myCircle:setFillColor(128,128,128)
myCircle.name=i
myCircle:addEventListener("touch",newLine)
end
I have a problem. According to the code below, I create an object x times (in this case 20 times) and add into a ballGroup. Moreover every one object should has body and react on "collision" physics event. But all of created balls haven't assigned body property (after putting them into ballGroup). So I think there is a problem (when I insert ball into ballGroup). When I try to addBody to whole ballGroup (line with comment), only last ball has Body property. Any idea how to solve this problem?
ballGroup = display.newGroup();
ballGroup.collision = onCollision;
ballGroup:addEventListener("collision", ballGroup);
-- physics.addBody(ballGroup,"dynamic", {density = 1, friction = 0, bounce = 1, radius = 10});
for i = 1,20 do
spawnBall();
end
function spawnBall()
ball = display.newImage("image.png");
ball.x = math.random(-W/2, W/2);
ball.y = math.random(-H/2, H/2);
physics.addBody(ball,"dynamic", {density = 1, friction = 0, bounce = 1, radius = 10});
ballGroup:insert(ball);
end
function onCollision(event)
print("123");
end
Make your ball local everytime you call spawnball()
ballGroup = display.newGroup();
ballGroup.collision = onCollision;
ballGroup:addEventListener("collision", ballGroup);
-- physics.addBody(ballGroup,"dynamic", {density = 1, friction = 0, bounce = 1, radius = 10});
for i = 1,20 do
spawnBall();
end
function spawnBall()
local ball = display.newImage("image.png");
ball.x = math.random(-W/2, W/2);
ball.y = math.random(-H/2, H/2);
physics.addBody(ball,"dynamic", {density = 1, friction = 0, bounce = 1, radius = 10});
ballGroup:insert(ball);
ball.collision = onCollision
ball:addEventListener( "collision", ball )
end
function onCollision(event)
print("123");
end
I'm trying to create a break breaker game that contains brinks that can be hit twice before the disappear.
I have tried:
--FOR STRONGER DEFENDERS
for i = 1, len do
for j = 1, level_W do
if(level[i][j] == 2) then
local strong = display.newImage('images/strongdefender.png')
strong.name = 'strong'
strong.x = def_W * j - offset
strong.y = def_H * i
physics.addBody(strong, {density = 1, friction = 0, bounce = 0})
strong.bodyType = 'static'
strongs.insert(strongs, strong)
end
end
end
for i = 1, len do
for j = 1, level_W do
if(level[i][j] == 2) then
local defender = display.newImage('images/defender.png')
defender.name = 'defender'
defender.x = def_W * j - offset
defender.y = def_H * i
physics.addBody(defender, {density = 1, friction = 0, bounce = 0})
defender.bodyType = 'static'
end
end
end
level is a table which is filled with 0 and 2. 2 is where the defender image will be in the game.
My collision event is like so:
function onCollision(e)
if(e.other.name == 'defender' or e.other.name == 'strong' and (ball.x + ball.width * 0.5) < (e.other.x + e.other.width * 0.5)) then
xSpeed = -5
elseif(e.other.name == 'defender' or e.other.name == 'strong' and (ball.x + ball.width * 0.5) >= (e.other.x + e.other.width * 0.5)) then
xSpeed = 5
end
if(e.other.name == 'defender') then
audio.play(defencePop)
ySpeed = ySpeed * -1
e.other:removeSelf()
e.other = nil
defenders.numChildren = defenders.numChildren - 1
--SORT SCORE
score = score + 1
scoreNum.text = score * points
scoreNum:setReferencePoint(display.CenterLeftReferencePoint)
scoreNum.x = 54
elseif(e.other.name == 'strong') then
audio.play(defencePop)
ySpeed = ySpeed * -1
e.other:removeSelf()
e.other = nil
defenders.numChildren = defenders.numChildren - 1
--SORT SCORE
score = score + 1
scoreNum.text = score * points
scoreNum:setReferencePoint(display.CenterLeftReferencePoint)
scoreNum.x = 54
end
--defenders.numChildren < 0
if(strongs.numChildren < 0) then
bgAlert('win')
gameStatus = 'win'
end
end -- removeDefender
When the ball collides with the element, both of them disappear. How can I make one disappear at a time?
I would suggest you just put the strong on the screen and add an event listener to them the weaker brick is created when the collision occurs with the stronger brick. The idea is to remove the object and add a new one when the collision occurs.
First you would display the strong object and add them to physics. You would also add a local collision event listener to the object
for i = 1, len do
for j = 1, level_W do
if(level[i][j] == 2) then
local strong = display.newImage('images/strongdefender.png')
strong.name = 'strong'
strong.x = def_W * j - offset
strong.y = def_H * i
physics.addBody(strong, {density = 1, friction = 0, bounce = 0})
strong.bodyType = 'static'
strong.collision = onBrickCollision --onStrongCollision is the name of the collision handler function
strong:addEventListener("collision" , strong) --add collision listener
strongs.insert(strongs, strong)
end
end
end
The event listener would be like
function onBrickCollision(self , event)
if event.phase == "began" and event.other.name == "ball" then
if (ball.x + ball.width * 0.5) < (self.x + self.width * 0.5) then
xSpeed = -5
else
xSpeed = 5
end
if self.name == "strong" then
audio.play(defencePop)
ySpeed = ySpeed * -1
--Create defender on the position of strong and add it to physics
local defender = display.newImage('images/defender.png')
defender.name = 'defender'
set the position same as the object which is hit by ball
defender.x = self.x
defender.y = self.y
physics.addBody(defender, {density = 1, friction = 0, bounce = 0})
defender.bodyType = 'static'
defender.collision = onBrickCollision
defender:addEventListener("collision", defender)
--remove the strong brick
self:removeSelf()
self = nil
--SORT SCORE
score = score + 1
scoreNum.text = score * points
scoreNum:setReferencePoint(display.CenterLeftReferencePoint)
scoreNum.x = 54
elseif self.name == "defender" then
audio.play(defencePop)
ySpeed = ySpeed * -1
self:removeSelf()
self = nil
defenders.numChildren = defenders.numChildren - 1
--SORT SCORE
score = score + 1
scoreNum.text = score * points
scoreNum:setReferencePoint(display.CenterLeftReferencePoint)
scoreNum.x = 54
end
end
Hope the code is self explanatory :) Feel free to ask me if you have any further questions.
How to make this spawn 'math.random(1,3)' smile.png every 10 seconds , and delete the smile.png after the left screen
<code>
local physics = require ("physics");
physics.start();
local function listener(me)
transition.to (me, {time = math.random(1000,4000), x = math.random(10,310), y = -30, onComplete = function()listener(me)end});
end
--Spawning multiple objects in randoms locations
local function spawnsmile()
local smile = display.newImageRect("smile.png", 45, 45);
smile:setReferencePoint(display.CenterReferencePoint);
smile.x = math.random(-10, 400);
smile.y = -40;
transition.to( smile, {time = math.random(2000, 8000), x = math.random(-10, 400) , y = 600,});
physics.addBody(smile, "dynamic", {density = 0.1, bounce = 0.1, friction = .1, radius = 0});
--Adding touch event
smile:addEventListener("touch", smile);
end
tmr = timer.performWithDelay(0, spawnsmile, total_smiles);
<code>
Regards Kevin
Your code was missing total_smiles value assignment and delay argument.
Working code:
local physics = require ("physics");
physics.start();
local function listener(me)
transition.to (me, {time = math.random(1000,4000), x = math.random(10,310), y = -30, onComplete = function()listener(me)end});
end
--Spawning multiple objects in randoms locations
local function spawnsmile()
local smile = display.newImageRect("Button.png", 45, 45);
smile:setReferencePoint(display.CenterReferencePoint);
smile.x = math.random(-10, 400);
smile.y = -40;
transition.to( smile, {time = math.random(2000, 8000), x = math.random(-10, 400) , y = 600,});
physics.addBody(smile, "dynamic", {density = 0.1, bounce = 0.1, friction = .1, radius = 0});
--Adding touch event
smile:addEventListener("touch", smile);
end
local total_smiles = 15
tmr = timer.performWithDelay(10000, spawnsmile, total_smiles);
Moreover, you should store references to created smiles in order to properly destroy them and don't leak memory. more info on memory managment
local smiles = {}
table.insert(smiles, smile)
And disposal:
for i=#smiles,1,-1 do
smiles[i]:removeSelf()
smiles[i] = nil
end
change your timer to perform every 10.000 ms instead of 0. And your listener function doesnt really fill any purpose, remove that and change your transition.to inside of spawnsmile function to
transition.to( smile, {time = math.random(2000, 8000), x = math.random(-10, 400) , y = 600, onComplete = function(obj) obj:removeSelf() obj = nil end});
That should do what you want it to do =) Also there needs to be a value inside total_smiles, but i guess you have it elsewhere.