LUA collision, Multiple Objects - lua

I have a program where a player will be dodging falling asteroids, the asteroids will have to pass through the ground and hit each other without ending the game. However, if an asateroid hits a player the game will need to end and display the game over screen. How do I differentiate between the contacts.
Here is my code so far:
--Start the physics engine!
local physics = require ("physics")
--Get a background image!
local background = display.newImage("Images/Background.png")
-- Hide status bar
display.setStatusBar(display.HiddenStatusBar);
--Is this guy even alive?
local PlayerAlive = true;
--What size is our screen?
_H = display.contentHeight;
_W = display.contentWidth;
--Play some tunes!
local music = audio.loadStream("Sounds/bf3.mp3");
--World is flat and small!
local leftWall = display.newRect (0, 0, 1, display.contentHeight);
local rightWall = display.newRect (display.contentWidth, 0, 1, display.contentHeight);
physics.addBody (leftWall, "static", { bounce = 0.1 } );
physics.addBody (rightWall, "static", { bounce = 0.1 } );
leftWall.myName = "Left wall"
rightWall.myName = "Right wall"
--Discover Gravity!
physics.setGravity(0, 1)
--5 Random numbers!
local Rock1Y = Math.Random(20)
local Rock2Y = Math.Random(20)
local Rock3Y = Math.Random(20)
local Rock4Y = Math.Random(20)
local Rock5Y = Math.Random(20)
if (Rock1Y == Rock2Y)then
end
--Create our rock!
local MyRock1 = display.newImage("Images/Rock.png", 25, 25)
local MyRock2 = display.newImage("Images/Rock.png", 25, 25)
local MyRock3 = display.newImage("Images/Rock.png", 25, 25)
local MyRock4 = display.newImage("Images/Rock.png", 25, 25)
local MyRock5 = display.newImage("Images/Rock.png", 25, 25)
--Add physics to our rock!
physics.addBody(MyRock1, "dynamic", {density = 1, friction = 0.0, bounce = 0.9, radius=10)
MyRock1.myName = "Rock 1"
physics.addBody(MyRock2, "dynamic", {density = 1, friction = 0.0, bounce = 0.9, radius=10)
MyRock2.myName = "Rock 2"
physics.addBody(MyRock3, "dynamic", {density = 1, friction = 0.0, bounce = 0.9, radius=10)
MyRock3.myName = "Rock 3"
physics.addBody(MyRock4, "dynamic", {density = 1, friction = 0.0, bounce = 0.9, radius=10)
MyRock4.myName = "Rock 4"
physics.addBody(MyRock5, "dynamic", {density = 1, friction = 0.0, bounce = 0.9, radius=10)
MyRock5.myName = "Rock 5"
--Where should MyRock be?
MyRock1.x = Random(10, _W-50) --Rock 1
MyRock1.y = Random(_H+Rock1Y)
MyRock2.x = Random(10, _W-50) --Rock 2
MyRock2.y = Random(_H+Rock2Y)
MyRock3.x = Random(10, _W-50) --Rock 3
MyRock3.y = Random(_H+Rock3Y)
MyRock4.x = Random(10, _W-50) --Rock 4
MyRock4.y = Random(_H+Rock4Y)
MyRock5.x = Random(10, _W-50) --Rock 5
MyRock5.y = Random(_H+Rock5Y)
--Here goes the character!
local character = display.newImage("Images/Character.png", display.contentWidth/2, 0)
physics.addBody(character, "dynamic", {density = 0, friction = 0.0, bounce = 0.9, radius = 2)
character.myName = "Character"
--Check for collision with character
local function onCollision( event )
if ( event.phase == "began" ) then
--IF THE PLAYER IS HIT ADD THIS CODE BRENDAN DO IT TONIGHT
end
end

the collision event object has information about the objects that collided. You could do something like this:
if event.object1 == character or event.object2 == character then
print( "character was hit!" )
--end game and display game over code
end
Read more here:
http://docs.coronalabs.com/api/event/collision/index.html

Related

How to create a heap of balls and keep it within the screen on ground in lua and corona sdk?

How to create a heap of balls and keep it within the screen on the ground in lua and corona sdk?
Right now it is falling down from the screen and disappear from the screen.
local physics = require("physics")
physics.start()
--local sky = display.newImage("sky.png")
--sky:scale( 5, 10 )
--sky.x = -100
--sky.y = -200
local field = display.newImage("field.png")
field:scale( 5, 10 )
field.x = 240
field.y = 470
local sky = display.newImage("sky.png")
sky:scale( 10, 3 )
physics.addBody(field,{friction = 0.5})
field.bodyType = "static"
local football = display.newImage("football.png")
football.x = 180
football.y = 80
football.rotation = 20
physics.addBody(football,{density = 2.0,friction = 0.5,bounce =0.5})
local function fallingball_field()
local football = display.newImage("football.png")
football.x = math.random(400)
football.y = -100
football.rotation = 20
physics.addBody(football, { density = 4.0,friction = 0.5, bounce = 0.5})
end
timer.performWithDelay(200, fallingball_field,200)
In order to put your physics objects within the screen you must create a "Boundary box" that will keep your ball within the screen. Bellow is an example on how to create a boundary:
local physics = require("physics")
physics.start()
physics.setDrawMode("hybrid")
local myCircle = display.newCircle( 100, 100, 30 )
myCircle:setFillColor( 0.5 )
local leftWall = display.newRect(0,display.contentCenterY, 10, display.contentHeight)
local rightWall = display.newRect(display.contentWidth,display.contentCenterY, 10, display.contentHeight)
local bottomWall = display.newRect(display.contentCenterX, display.contentHeight - 25, display.contentWidth, 10)
local topWall = display.newRect(display.contentCenterX, 25, display.contentWidth, 10)
leftWall:setFillColor(nil)
rightWall:setFillColor(nil)
bottomWall:setFillColor(nil)
topWall:setFillColor(nil)
physics.addBody (leftWall, "static", { bounce = 0.1} )
physics.addBody (rightWall, "static", { bounce = 0.1} )
physics.addBody (bottomWall, "static", { bounce = 0.1} )
physics.addBody (topWall, "static", { bounce = 0.1} )
physics.addBody (myCircle, "dynamic", { bounce = 1.5} )
Explanation:
The "walls" will keep your physics objects into place assuming that your app is set to horizontal this will work as is. let me know if your application is vertical.
The physics.setDrawMode("hybrid") will show the physics boundaries of EACH objects that you set with a physics body.It will be easier to see how your objects interact to each other.

have one image negate the collision detection of another image

i have a water image that kills the user sprite on collision, taking 1 from the lives variable and re-spawns the sprite to the start. i have another image of a raft that constantly spawn new images that move across the screen. im trying to get it so the user can move onto the raft, that is over the water image, and not get re-spawned back to the start.
--sets the function for the death sequence.
function waterCollide(event)
frog.x = display.contentWidth/2
frog.y = 504
isOnRaft = 0
lives = lives - 1
showlives.text = "Lives: "..lives,230,-36,native.systemFont,25
lose()
end
--sets water
water = display.newRect(0,0,320,150)
water.x = display.contentWidth*0.5
water.y = 144
water.alpha = 0
physics.addBody(water,"static", {isSensor = true})
water:addEventListener("collision", function ()timer.performWithDelay(50,waterCollide)end)
--Set log position and movement
local mRandom = math.random
local raft = {"Raft1" ,"Raft2"}
local objectTag = 0
local object = {}
function spawnlogleft()
objectTag = objectTag + 1
local objIdx = mRandom(#raft)
local objName = raft[objIdx]
object[objectTag] = display.newImage(objName..".png")
object[objectTag].x = -96
object[objectTag].y = 216
object[objectTag].name = objectTag
transition.to(object[objectTag], {time = 10000, x = 416, onComplete = function(obj) obj:removeSelf(); obj = nil; end})
physics.addBody( object[objectTag], "static",{isSensor = true})
end
spawnlogleft()
timer.performWithDelay(3500,spawnlogleft,0)
--user sprite details
frog = display.newSprite(frogSheet, sequenceData)
frog.x = display.contentWidth/2
frog.y = 504
physics.addBody( frog, "dynamic", physicsData:get("FrogSheetData"))
frog.isFixedRotation = true
the user sprite is an animation of three frames and a time of 300. any help would be appreciated. and i will provide more details if needed.
thank you
Corona has these neat things called CollisionFilters. They show you how to use them in /Physics/CollisionFilter.
You basically set bits to make certain objects un-collideable with other objects. Check this main.lua example out:
local physics = require("physics")
physics.start()
physics.setScale( 60 )
display.setStatusBar( display.HiddenStatusBar )
local bkg = display.newImage( "stripes.png" )
borderCollisionFilter = { categoryBits = 1, maskBits = 6 } -- collides with (4 & 2) only
borderBodyElement = { friction=0.4, bounce=0.8, filter=borderCollisionFilter }
local borderTop = display.newRect( 0, 0, 320, 1 )
borderTop:setFillColor( 0, 0, 0, 0) -- make invisible
physics.addBody( borderTop, "static", borderBodyElement )
local borderBottom = display.newRect( 0, 479, 320, 1 )
borderBottom:setFillColor( 0, 0, 0, 0) -- make invisible
physics.addBody( borderBottom, "static", borderBodyElement )
local borderLeft = display.newRect( 0, 1, 1, 480 )
borderLeft:setFillColor( 0, 0, 0, 0) -- make invisible
physics.addBody( borderLeft, "static", borderBodyElement )
local borderRight = display.newRect( 319, 1, 1, 480 )
borderRight:setFillColor( 0, 0, 0, 0) -- make invisible
physics.addBody( borderRight, "static", borderBodyElement )
local red = {}
local blue = {}
local redCollisionFilter = { categoryBits = 2, maskBits = 3 } -- collides with (2 & 1) only
local blueCollisionFilter = { categoryBits = 4, maskBits = 5 } -- collides with (4 & 1) only
local redBody = { density=0.2, friction=0, bounce=0.95, radius=43.0, filter=redCollisionFilter }
local blueBody = { density=0.2, friction=0, bounce=0.95, radius=43.0, filter=blueCollisionFilter }
for i = 1,4 do
red[i] = display.newImage( "red_balloon.png", (80*i)-60, 50 + math.random(20) )
physics.addBody( red[i], redBody )
red[i].isFixedRotation = true
blue[i] = display.newImage( "blue_balloon.png", (80*i)-60, 250 + math.random(20) )
physics.addBody( blue[i], blueBody )
blue[i].isFixedRotation = true
end

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

collision event and display.newGroup. How to connect them together? Corona

I have a problem. According to the code below, I create an object x times (in this case 20 times) and add into a ballGroup. Moreover every one object should has body and react on "collision" physics event. But all of created balls haven't assigned body property (after putting them into ballGroup). So I think there is a problem (when I insert ball into ballGroup). When I try to addBody to whole ballGroup (line with comment), only last ball has Body property. Any idea how to solve this problem?
ballGroup = display.newGroup();
ballGroup.collision = onCollision;
ballGroup:addEventListener("collision", ballGroup);
-- physics.addBody(ballGroup,"dynamic", {density = 1, friction = 0, bounce = 1, radius = 10});
for i = 1,20 do
spawnBall();
end
function spawnBall()
ball = display.newImage("image.png");
ball.x = math.random(-W/2, W/2);
ball.y = math.random(-H/2, H/2);
physics.addBody(ball,"dynamic", {density = 1, friction = 0, bounce = 1, radius = 10});
ballGroup:insert(ball);
end
function onCollision(event)
print("123");
end
Make your ball local everytime you call spawnball()
ballGroup = display.newGroup();
ballGroup.collision = onCollision;
ballGroup:addEventListener("collision", ballGroup);
-- physics.addBody(ballGroup,"dynamic", {density = 1, friction = 0, bounce = 1, radius = 10});
for i = 1,20 do
spawnBall();
end
function spawnBall()
local ball = display.newImage("image.png");
ball.x = math.random(-W/2, W/2);
ball.y = math.random(-H/2, H/2);
physics.addBody(ball,"dynamic", {density = 1, friction = 0, bounce = 1, radius = 10});
ballGroup:insert(ball);
ball.collision = onCollision
ball:addEventListener( "collision", ball )
end
function onCollision(event)
print("123");
end

corona set physics limitation

How can I make my game character's physic is limited only to 'tilt' left and right a bit? Here's how I declared my character
collector = display.newImage ("ms_throw.png")
collector.x = 10
collector.y = 10
physics.addBody(collector, {friction = 1.0, bounce = 0.6})
ms_throw.png is an image of a man standing... so basically collector will move left to right (using accelerometer) and I need the actor to only tilt a bit when he's moving.. means I don't want it to turn upside down when I tilt the phone.. How do I achieve this?
The trick is to tweak the coordinatey of applyForce(forcex,forcey,coordinatex,coordinatey).
If there is significant friction, the object will tilt.
To limit the tilt angle, use a box to cage it.
local physics = require("physics")
physics.start()
physics.setGravity(0,10)
centerx = display.viewableContentWidth/2+(display.contentWidth-display.viewableContentWidth)/2
centery = display.viewableContentHeight/2+(display.contentHeight-display.viewableContentHeight)/2
borderx = (display.contentWidth-display.viewableContentWidth)/2
bordery = (display.contentHeight-display.viewableContentHeight)/2
local w = display.viewableContentWidth/2
local h = 100/2
local allowanceHeight = 15
local collectorLimiter = {}
--cannot do in createScene because need to do together with physics
local ix,iy = centerx,bordery+display.viewableContentHeight-60
collectorLimiter[1] = display.newRect(0,0,display.viewableContentWidth,4)
collectorLimiter[1].x,collectorLimiter[1].y = ix,iy-h-allowanceHeight
collectorLimiter[2] = display.newRect(0,0,display.viewableContentWidth,4)
collectorLimiter[2].x,collectorLimiter[2].y = ix,iy+h
collectorLimiter[3] = display.newRect(0,0,4,h*2+allowanceHeight)
collectorLimiter[3].x,collectorLimiter[3].y = ix-w,iy
collectorLimiter[4] = display.newRect(0,0,4,h*2+allowanceHeight)
collectorLimiter[4].x,collectorLimiter[4].y = ix+w,iy
for i = 1,#collectorLimiter do
--collectorLimiter[i].isVisible = false
end
physics.addBody(collectorLimiter[1],"static", {friction = 0.3,bounce = 0, filter = {categoryBits = 4,maskBits = 6} })
physics.addBody(collectorLimiter[2],"static", {friction = 0.3,bounce = 0, filter = {categoryBits = 4,maskBits = 6} })
physics.addBody(collectorLimiter[3],"static", {friction = 0.3,bounce = 0, filter = {categoryBits = 4,maskBits = 6} })
physics.addBody(collectorLimiter[4],"static", {friction = 0.3,bounce = 0, filter = {categoryBits = 4,maskBits = 6} })
local collector = display.newRect(0,0,80,100)
collector.x,collector.y = centerx,centery+480
physics.addBody(collector, {friction = 0.3, density = 0.2, bounce = 0, filter = {categoryBits = 2}} )
local function OnTouch(event)
-- Move our collector based on the accelerator values
if event.phase == "began" then
collector.ix,collector.iy = event.x,event.y
elseif event.phase == "moved" then
if collector.ix and collector.iy then
local dx = (event.x-collector.ix)*0.4
collector:applyForce(dx,0,collector.x,collector.y-10)
collector.ix,collector.iy = collector.x,collector.y
end
elseif event.phase == "ended" or event.phase == "cancelled" then
collector.ix,collector.iy = nil,nil
end
end
Runtime:addEventListener("touch",OnTouch)

Resources