Flipboard Effect on Corona SDK using Lua - 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.

Related

Check Winner Naughts and Crosses game - Lua/Corona

I am quite new to the Lua language and am trying to create a simple Tic Tac Toe game. I am having difficulties figuring out how to check the winner. I have tried if-then statements but I think I am using them wrong. Not sure what the best way to check the winner is so any suggestions or assistance is greatly appreciated.
The code is -
local composer = require( "composer" )
local scene = composer.newScene()
d = display
w20 = d.contentWidth * .2
h20 = d.contentHeight * .2
w40 = d.contentWidth * .4
h40 = d.contentHeight * .4
w60 = d.contentWidth * .6
h60 = d.contentHeight * .6
w80 = d.contentWidth * .8
h80 = d.contentHeight * .8
----DRAW LINES FOR BOARD
local lline = d.newLine(w40,h20,w40,h80 )
lline.strokeWidth = 5
local rline = d.newLine(w60,h20,w60,h80 )
rline.strokeWidth = 5
local bline = d.newLine(w20,h40,w80,h40 )
bline.strokeWidth = 5
local tline = d.newLine(w20,h60,w80,h60 )
tline.strokeWidth = 5
--PLACE BOARD COMPARTMENT DIMENSIONS IN TABLE
board ={
{"tl",1,w20,h40,w40,h20,0},
{"tm",2,w40,h40,w60,h20,0},
{"tr",3,w60,h40,w80,h20,0},
{"ml",4,w20,h60,w40,h40,0},
{"mm",5,w40,h60,w60,h40,0},
{"mr",6,w60,h60,w80,h40,0},
{"bl",7,w20,h80,w40,h60,0},
{"bm",8,w40,h80,w60,h60,0},
{"br",9,w60,h80,w80,h60,0}
}
--
local EMPTY, X, O = 0, 1, 2
local whichTurn = 0
--FILL COMPARTMENT W/ COLOUR WHEN TOUCHED
local function fill(event)
if (event.phase == "ended") then
for t = 1,9 do
if event.x > board[t][3] and event.x < board[t][5] then
if event.y < board[t][4] and event.y > board[t][6] then
if board[t][7] == EMPTY then
if whichTurn == 1 then
whichTurn = 2
else
whichTurn = 1
end
board[t][7] = whichTurn
if board[t][7] == 1 then
local xText = display.newText("X", board[t][3], board[t][4], "Arial", 80)
xText.anchorX = 0
xText.anchorY = 100
elseif board[t][7] == 2 then
local oText = display.newText("O", board[t][3], board[t][4], "Arial", 80)
oText.anchorX = 0
oText.anchorY = 100
end
end
end
end
end
end
local function checkWinner()
for i = 1,9 do
if board[i][2] == 1 and board[i][7] == 1 then
boxOne = "x"
end
if board[i][2] == 2 and board[i][7] == 1 then
boxTwo = "x"
end
if board[i][2] == 3 and board[i][7] == 1 then
boxThree = "x"
end
if boxOne == "x" and boxTwo == "x" and boxThree == "x" then
display.newText("Winner", 10, 100, "Arial", 200)
end
end
end
end
Runtime:addEventListener ("touch", fill)
return scene
local All_Lines = {{1,5,9}, {3,5,7}, {1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8}, {3,6,9}}
local function checkWinner()
for _, Line in ipairs(All_Lines) do
local values = 0
for _, idx in ipairs(Line) do
values = values * 10 + board[idx][7]
end
if values == 111 then
display.newText("Winner", 10, 100, "Arial", 200)
return
elseif values == 222 then
display.newText("Loser", 10, 100, "Arial", 200)
return
end
end
end

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

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/

Zoom on touch event

I'm trying to put in place a zoom function on touch event. I scale the parent group using transition.to and onComplete move it to the event center. But then at one point it just jumps to the parent group origin. Any ideas?
I'm now pasting a shortened version of the code.
local physics = require( "physics" )
physics.start()
physics.setContinuous( false )
--physics.setScale( 60 )
local height = display.contentHeight
local width = display.contentWidth
local backGround = display.newRect( 0,0,width,height )
backGround:setFillColor(91,91,91)
local allElements = display.newGroup()
local grip = {}
local gripSize = {
-- w: gripwidth, h: gripheight, s: strength required
{w=30, h=20, s=1},
{w=20, h=10, s=1.5},
{w=10, h=10, s=2},
}
local r
local function createTexture()
local originX = 0
local originY = height -75
for i=0,50 do
r = math.random(3)
local x = originX + math.random(width)
local y = originY - math.random(2*height)
grip[i] = display.newRect( allElements, x, y, gripSize[r].w, gripSize[r].h)
grip[i].size = gripSize[r].s
if (r == 1) then
grip[i]:setFillColor(51,255,0)
elseif (r == 2) then
grip[i]:setFillColor(255,51,51)
elseif (r == 3) then
grip[i]:setFillColor(51,51,255)
end
end
end
createTexture()
wallBottom = display.newRect( allElements, 0,height-20,width,20)
physics.addBody(wallBottom, "static", { density=5, friction=0.5, bounce=0.3 } )
head = display.newCircle( allElements, width/2,50,20 )
physics.addBody( head, { density=5, friction=0.5, bounce=0.3 } )
local touchBorder = 20
local function calcTouchOffset( e )
local x, y = 0, 0
if (e.x < touchBorder) then
x = e.x - touchBorder
elseif (e.x > width-touchBorder) then
x = e.x - (width-touchBorder)
end
if (e.y < touchBorder) then
y = e.y - touchBorder
elseif (e.y > height-touchBorder) then
y = e.y - (height-touchBorder)
end
return x, y
end
local function startDrag( e )
local body = e.target
local phase = e.phase
local stage = display.getCurrentStage()
if (e.phase == "began") then
e.target.bodyType = "dynamic"
e.target.hasFocus = true
local x, y = allElements:contentToLocal( e.x, e.y )
e.target.touchjoint = physics.newJoint( "touch", e.target, x, y )
stage:setFocus( e.target )
transition.to( allElements, { time = 200, x= -body.x, y= -body.y, xScale = 2, yScale = 2,})
xOffset, yOffset = 0, 0
return true
elseif (e.target.hasFocus) then
if (e.phase == "moved") then
local x,y = allElements:contentToLocal(e.x, e.y) -- This line is changed
e.target.touchjoint:setTarget( x, y ) -- This line is changed
xOffset, yOffset = calcTouchOffset( e )
else
transition.to( allElements, { time = 200, x = body.x, y = body.y, xScale = 1, yScale = 1, })
e.target.hasFocus = false
e.target.touchjoint:removeSelf()
e.target.touchjoint = nil
stage:setFocus( nil )
xOffset, yOffset = 0, 0
end
return true
end
xOffset, yOffset = 0, 0
return false
end
head:addEventListener( "touch", startDrag )
function allElements:update()
allElements.x, allElements.y = allElements.x - xOffset, allElements.y - yOffset
allElements.x, allElements.y = allElements.x, allElements.y
if (allElements.x > -startX) and ( startX < 0 ) then
allElements.x = -startX
elseif ( routeW < width ) then
allElements.x = 0
elseif ( allElements.x < startX ) and ( startX < 0 ) then
allElements.x = startX
end
--[[if (allElements.x > 0) then
allElements.x = 0
elseif ( routeW < width ) then
allElements.x = 0
elseif ( allElements.x < (width-routeW) ) and ( routeW > width ) then
allElements.x = width-routeW
end ]]--
if (allElements.y > (routeH-height)) and ( routeH > height ) then
allElements.y = routeH-height
elseif ( routeH < height ) then
allElements.y = 0
elseif (allElements.y < 0) then
allElements.y = 0
end
end
function enterFrame()
allElements:update()
end
You just need to update this part:
elseif (e.target.hasFocus) then
if (e.phase == "moved") then
local x,y = allElements:contentToLocal(e.x, e.y) -- This line is changed
e.target.touchjoint:setTarget( x, y ) -- This line is changed
xOffset, yOffset = calcTouchOffset( e )
else
transition.to( allElements, { time = 200, x = 0, y = 0, xScale = 1, yScale = 1, })
e.target.hasFocus = false
e.target.touchjoint:removeSelf()
e.target.touchjoint = nil
stage:setFocus( nil )
xOffset, yOffset = 0, 0
end
return true
end
By replacing x=body.x by x=0 and y=body.y by y=0
Cheers :)

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

Resources