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

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.

Related

I got an error here in main.lua: 178: attempt to index global 'pausebutton' (a nil value)

I got an error in Corona's simulator console in main.lua
attempt to index global pausebutton (a nil value)
How to solve my problem with Corona error?
The most revelant code from main.lua file I put below
-- Display the pause button
function pauseAndResume ()
local pausebutton = display.newImage ("pause.png")
pausebutton : translate(100, 100)
pausebutton:addEventListener ("touch" , pauseGame)
local resumebutton = display.newImage ("resumed.png")
resumebutton: translate(100, 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
I think you got error because local variables pausebutton and resumebutton exist only during executing of pauseAndResume function. After that they gone. So you need declare them in the block in which they will be available for pauseAndResume and pauseGame functions, for example on begining of the main.lua file.
Try
local pausebutton
local resumebutton
...
-- Display the pause button
function pauseAndResume ()
pausebutton = display.newImage ("pause.png")
pausebutton : translate(100, 100)
pausebutton:addEventListener ("touch" , pauseGame)
resumebutton = display.newImage ("resumed.png")
resumebutton: translate(100, 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
From Lua documentation
We create local variables with the local statement:
j = 10 -- global variable
local i = 1 -- local variable
Unlike global variables, local variables have their scope limited to
the block where they are declared. A block is the body of a control
structure, the body of a function, or a chunk (the file or string with
the code where the variable is declared).
-- Samurai Fruit
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 ()
local pausebutton = display.newImage ("pause.png")
pausebutton : translate(100, 100)
pausebutton:addEventListener ("touch" , pauseGame)
local resumebutton = display.newImage ("resumed.png")
resumebutton: translate(100, 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.strokeWidth = 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, strokeWidth = 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, strokeWidth = 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.strokeWidth = lineThickness
transition.to(line, {time = lineFadeTime, alpha = 0, strokeWidth = 0, onComplete = function(event) line:removeSelf() end})
end
if(event.phase == "ended") then
while(#endPoints > 0) do
table.remove(endPoints)
end
end
end
main()

Receiving "Attempt to index global 'sprite' (a nil value)" in Lua

Im attempting to make a simple game app and keep running into this problem. I stopped programming in Lua for a few years so I don't exactly remember how to fix this. Anyway, my code is as follows:
EDIT: Here is the entire file. Still trying to figure out the formatting of Stack Overflow. Error occurs at line 76.
module(..., package.seeall)
-- Main function - MUST return a display.newGroup()
function new()
local localGroup = display.newGroup()
---------
local Rad = math.rad
local Sin = math.sin
local Cos = math.cos
local Pi = math.pi
local Atan2 = math.atan2
local radD = 180 / Pi
local DegR = Pi / 180
local touchPoint = display.newCircle(localGroup, -50, -50, 20)
touchPoint.isFocus = false
touchPoint.alpha = 0
function GetDistanceFromObjects(obj1, obj2)
local xDist = obj1.x - obj2.x
local yDist = obj1.y - obj2.y
local dist = Sqrt((xDist * xDist) + (yDist * yDist))
return dist
end
function getAngleDeg(inX1, inY1, inX2, inY2)
local xDist = inX2 - inX1
local yDist = inY2 - inY1
local angRad = Atan2(yDist, xDist)
return angRad * radD + 90
end
require "sprite"
function VectorFromAngle(inAngle, inVelocity)
local vx = Cos(Rad(inAngle-90))
local vy = Sin(Rad(inAngle-90))
if(inVelocity ~= nil)then
vx = vx * inVelocity
vy = vy * inVelocity
end
return vx,vy
end
require ( "physics" )
physics.start()
physics.setGravity( 1, 1 )
--( x, y )
--physics.setDrawMode ( "hybrid" )
math.randomseed(os.time())
local background = display.newImage("yazd.jpeg")
localGroup:insert(background)
--width of image divided by # of pics lined up from left to right (in the sprite) = the first #
--height of image divided by # of pics lined up from top to bottom (in the sprite) = the second #
local birdSheet = sprite.newSpriteSheet( "enemy.jpg", 59, 50 )
local birdSet = sprite.newSpriteSet(birdSheet, 1, 1)
-- images 1-14
sprite.add( birdSet, "bird", 1, 1, 200, 0 )
-- play 1-14, each image every 200 ms, 0 = loop count, which is infinite
local bird1 = sprite.newSprite( birdSet )
bird1.x = 40 -- starting point
bird1.y = 40 -- starting point
bird1.xScale = 0.5 --scale down x
bird1.yScale = 0.5 --scale down y
bird1:prepare("bird") --prepare sprite sequence
bird1:play() --play sprite
localGroup:insert(bird1)
--only local to this group
local killSheet = sprite.newSpriteSheet("explosion.png", 100, 100)
local killSet = sprite.newSpriteSet(killSheet, 1, 9)
sprite.add(killSet, "kill", 1, 9, 200, 1)
local birdCount = 1
local transDirection12
local function transDirection1()
bird1.xScale = 0.5
transition.to(bird1, {time=math.random(200,500), x = math.random(200,490), y = math.random(10,310), alpha = (math.random(9,100))/100, onComplete = transDirection12})
end
transDirection12 = function()
bird1.xScale = 0.5
transition.to(bird1, {time= math.random(200,500), x = math.random(200,490), y = math.random(10,310), alpha = (math.random(9,100))/100, onComplete = transDirection1})
end
transDirection1()
-- local transDirection1 declares what will be used (local function)
-- transDirection1 = function
-- following it are the function qualities
-- declares it will use object/image called bird1 and scales it to .5
-- time = ____ means it will take a certain time, between ____ and ____ to complete the transition
-- x=____ means that is where it will move to on the x axis
-- y=____ means that is where it will move to on the y axis
-- alpha = ___ means the is how transparent it will be
-- onComplete = ________ means that when the action is complete, it will call another function
-- The next function has the same qualities as transDirection1, but the onComplete part calls transDirection1 and they continue to loop
-- transDirection1() declares transDirection1 so the app knows about it and can use it
-- the other trans do not need to be declared because they are part of transDirection1, which is already declared
--(x, y, size.x, size.y)
local player = display.newImage( "mk11.png" )
player.x = 240
player.y = 260
player.xScale = .5
player.yScale = .5
localGroup:insert( player )
-- add physics to all the objects wanted: (object wanted, "static" or "dynamic")
physics.addBody(player, "static", {radius=30, isSensor = true})
physics.addBody(bird1, "static", {radius=23})
local function shoot(inPointX, inPointY)
-- (start at the x of the player + 10, also start at the y of the player, the radius of the circle is 5)
local bullet = display.newImage( "bullet2.png" )
bullet.x = player.x
bullet.y = player.y
-- add physics to the object, which is the bullet.
-- Make the bullet "dynamic" or moving
physics.addBody(bullet, "dynamic")
bullet.isFixedRotation = true
localGroup:insert( bullet )
local velocity = 300
local vx, vy = VectorFromAngle(player.rotation, velocity)
bullet.rotation = player.rotation
bullet:setLinearVelocity(vx, vy)
end
function RotateToTouchPoint(inPointX, inPointY)
local ang = getAngleDeg(player.x, player.y, inPointX, inPointY)
player.rotation = ang
end
local function ScreenTouchListener(event)
local phase = event.phase
if(phase == "began")then
if(touchPoint.isFocus == false)then
touchPoint.alpha = 1
touchPoint.x = event.x
touchPoint.y = event.y
display.getCurrentStage():setFocus(touchPoint, event.id)
touchPoint.isFocus = true
RotateToTouchPoint(event.x, event.y)
shoot(event.x, event.y)
end
elseif(touchPoint.isFocus)then
if(phase == "moved")then
touchPoint.x = event.x
touchPoint.y = event.y
RotateToTouchPoint(event.x, event.y)
elseif(phase == "ended" or phase == "cancelled")then
display.getCurrentStage():setFocus(touchPoint, nil)
touchPoint.isFocus = false
touchPoint.alpha = 0
end
end
return true
end
local function gotShot (event)
event.target:removeSelf()
event.other:removeSelf()
local explosion = sprite.newSprite(killSet)
explosion.x, explosion.y = event.target.x, event.target.y
explosion:prepare("kill")
explosion:play()
localGroup:insert( explosion )
birdCount = birdCount - 1
-- when there are no more birds, remove the runtime event listener and perform the
-- function with a delay of 500 m.s. The function changes the scene to test.lua
if "ended" then
if birdCount == 0 then
Runtime:removeEventListener("touch", ScreenTouchListener)
timer.performWithDelay(500, function()
director:changeScene("mainPage") end, 1)
end
end
end
bird1:addEventListener("collision", gotShot)
Runtime:addEventListener("touch", ScreenTouchListener)
---------
-- MUST return a display.newGroup()
return localGroup
end
Any help is appreciated!
The error message is perfectly clear -- the variable sprite used at this line:
local bird1 = sprite.birdSheet( birdSet )
has a nil value, meaning it has not been initialized or was set to nil. You need to show the earlier code where you should have set it up.
(After OP updates)
I think this line
require "sprite"
should actually be
sprite = require "sprite"
You can read more in modules tutorial here:
http://lua-users.org/wiki/ModulesTutorial

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

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 )
...

How to utilize combo scoring in Corona?

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

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.

Resources