Collision Filters not working - lua

Hi i am trying to get this collision filter to work but i am a little bit stuck...
local bad1CollisionFilter1 = { categoryBits = 1, maskBits = 3 }
if ( temp.imgpath == "BCloud1.png" ) then
physics.addBody( randomStar, { density=2.9, friction=0.5, bounce=0.3, radius=16, filter=bad1CollisionFilter1 } )
end
local collision = function( bad1CollisionFilter1 )
if bad1CollisionFilter1.phase == 'began' then
print("Hello i am CollisionFilter1")
end
end
Any help to get this working is appreciated!

By looking at the Corona API for collision and EventListener; you need to add an even listener with the body. Add the following statement to your script.
Runtime:addEventListener( "collision", collision )
where the first argument states that it is a collision event listener and the second argument is the function name; which in your case is collision.

Related

Coronasdk Issue with addeventListeners

recently I was coding a new game when I ran across a problem of which I cannot seem to be able to fix.
This is the code :
function newPower()
rand = math.random( 100 )
if (rand < 80) then
powerup = display.newImage("power.png");
powerup.class = "powerup"
powerup.x = 60 + math.random( 160 )
powerup.y = -100
physics.addBody( powerup, { density=0.9, friction=0.3, bounce=0.3} )
powerup:addEventListener( "touch", handlePowerTouch )
end
end
local function handlePowerTouch( event )
if event.phase == "began" then
currentScore = currentScore * 2
currentScoreDisplay.text = string.format( "%06d", currentScore )
event.target:removeSelf()
return true
end
end
local function spawnpowers()
-- Spawn a new powerup every second until canceled.
spawnPower = timer.performWithDelay( 1000, newPower, -1 )
end
Any help fixing this issue would be greatly appreciated!
The issue I'm having is when I click "run" or "play" the game starts working then crashes and displays this message:
addEventListener: listener cannot be nil: nil stack traceback:
?: in function 'addeventListener'
game.lua63: in function'_listener' <-- i have given you game.lua:63 above.
Thanks
powerup:addEventListener( "touch", handlePowerTouch )
Here handlePowerTouch is nil as the function definition follows after this line.
Move your function definition in front of that line, then it should work.
Btw, is there any reason why you have so many global variables? You should use local variables wherever possible.

Touch function not working

local Gin2
local function Gin ( event )
if ( event.phase == "began" ) then
Gin2 = display.newImage("PNGs/Sprite/Gin")
Gin2.x = _H
Gin2.y = _W
end
return true
end
Runtime:addEventListener("touch", Gin )
Hello, so I've been trying to figure out this for some time, but with with no success. So as may guess the idea is to spawn an image by touching.Should I define the object that will be touch?
I have made a code for you to use. When you want to spawn an object via touch listener (Either Runtime event or a single event) you can use event.x and event.y to determine the touch point of the user. Below is the code.
NOTE: I made gin as a array for future use of your spawned object
local val = 1
local gin = {}
local spawnObject = function(event)
if(event.phase == "ended") then
gin[val] = display.newImage("PNGs/Sprite/Gin")
gin[val].x = event.x
gin[val].y = event.y
val = val + 1
end
end
Runtime:addEventListener( "touch", spawnObject )
You are using the 'functional listener' form and for 'touch' event you should not be using Runtime.
In your case, you need to change Runtime to the object that 'is to be touched'. I guess what you want to do is to move the image once it is touched.
so, firstly move
Gin2 = display.newImage("PNGs/Sprite/Gin")
up and out the function. then change Runtime to Gin2.

Corona SDK : How to identify the collision object?

I'm a beginner in Corona developping and i've to problem to identify the collision between 3 objects. In fact, this is my code :
The first object is my player :
player = display.newImageRect("ballon.png", 150,170 )
player.anchorX = 0.5
player.anchorY = 0.5
player.x = display.contentCenterX - 450
player.y = display.contentCenterY+250
physics.addBody(player, "static", {density=0.1, bounce=0.1, friction=0.1,})
player.myName="player"
screenGroup:insert(player)
The second object is created within a function :
function addWindSlow(self,event)
height = math.random(display.contentCenterY - 200, display.contentCenterY + 200)
windslow = display.newImage( "wind-neg.png")
windslow.x = display.contentWidth
windslow.y = height
windslow.speed = 4
windslow.myName="windslow"
physics.addBody(windslow, "static", {density = 0.1, bounce = 0, isSensor = false})
elements:insert(windslow) end
function addWindFast(self,event)
height = math.random(display.contentCenterY - 200, display.contentCenterY + 200)
windfast = display.newImage( "wind-pos.png")
windfast.x = display.contentWidth
windfast.y = height
windfast.speed = 4
windfast.myName="windfast"
physics.addBody(windfast, "static", {density = 0.1, bounce = 0, isSensor = false})
elements:insert(windfast) end
And finally, the thirth object is the same but called "addWindFast() with a different image"
So i would like to know once my player is on collision with the windslow, i need to do an action... and if it's the object windfast, another action. That's my code :
function onCollision( event )
if ( event.phase == "began" ) then
if event.other.windslow and event.other.isVisible==true then
print("windslow has been touch !")
end
end
end
I found something about the pre-collision, I'll use it once i got the information how to "identify" the object...I'll need to prevent the collision and avoid it if the player is going to touch the windfast or windslow.
We thank you for all dude !
It looks like windslow and windfast are defined outside of onCollision event handler so you should compare to those:
function onCollision( event )
if ( event.phase == "began" ) then
if event.other == windslow and event.other.isVisible==true then
print("windslow has been touch !")
end
if event.other == windfast and event.other.isVisible==true then
print("windfast has been touch !")
end
end
end -- (missing from your post but probably in your code)
The above assumes that you have registered for collision events on your player. You could also register a different collision handler on each wind:
windslow:addEventListener("collision", onCollisionSlow)
windfast:addEventListener("collision", onCollisionFast)
In that case the two collision handlers could just check if event.other == player. The advantage of that is you are separating the code for each one. You could of course do the same with your player handler:
function onCollisionSlow(other)
print('collided with slow')
end
function onCollisionFast(other)
print('collided with fast')
end
collisionHandlers = {
[windslow] = onCollisionSlow,
[windfast] = onCollisionFast,
}
function onCollision( event )
if ( event.phase == "began" ) then
collisionFunc = collisionHandlers[event.other]
if collisionFunc ~= nil and event.other.isVisible then
collisionFunc(event.other)
end
end
end
You could identify the other object with the myName property you've specified.
For example:
function onCollision( event )
if ( event.phase == "began" ) then
if (event.other.myName == "windslow" and event.other.isVisible==true) then
print("windslow has been touched!")
elseif (event.other.myName = "windfast" and event.other.isVisible==true) then
print("windfast has been touched!")
end
end

Collision Detection with Ceramic Tile Engine & Box 2D

Follow up of this question, Storyboard with Ceramic Tile Engine, and with Collision Detection is still a mystery. Here is the code:
-- hide status bar
display.setStatusBar(display.HiddenStatusBar)
local storyboard = require("storyboard")
--Set up the physics world
local physics = require("physics")
physics.start()
physics.setGravity(0, 0)
physics.setDrawMode('hybrid')
local scene = storyboard.newScene()
local widget = require("widget")
-- Add Hero to Physics
local hero = display.newImage("images/man.png")
hero.x = 40
hero.y = 80
local heroCollisionFilter = { categoryBits = 4, maskBits = 2 }
local heroBody = { filter=heroCollisionFilter, isSensor=true }
physics.addBody(hero, "dynamic", heroBody)
function scene:createScene( event )
local group = self.view
local ceramic = require("Ceramic")
ceramic.showPrints = false
local map = ceramic.buildMap("maps/map.lua")
-- collisionLayer = map.layer['Collision']
-- collisionLayer.ccName = "map"
-- physics.addBody(collisionLayer, "static", { friction=0.5, bounce=0.3 } )
map.y = 0
map.setCameraDamping(10)
map.layer['World']:insert(hero)
end
function onGlobalCollision(event)
if(event.phase == "began") then
print( "Global report: " .. event.object1.ccName .. " & " .. event.object2.ccName .. " collision began" )
elseif(event.phase == "ended") then
print( "Global report: " .. event.object1.ccName .. " & " .. event.object2.ccName .. " collision ended" )
end
print( "**** " .. event.element1 .. " -- " .. event.element2 )
end
Runtime:addEventListener("collision", onGlobalCollision)
scene:addEventListener( "createScene", scene )
return scene
And the screenshot looks like:
However, collision never triggers, as the print message does not appear in Terminal at all.
I'm using:
Corona SDK
Ceramic Tile Engine
Corona module: storyboard, physics
How can I enable Collision Detection ? Are the parameters correct ?
Edit 2013/10/27
The Tiled map settings are as follow:
When running in Mac OS X, the collision does not happen ( only the hybrid layer changes color ).
When running in Windows 7, the code crashes on this line:
ceramic.buildMap("maps/map.lua")
with error:
attempt to call global 'reversePolygon' (a nil value) in Ceramic.lua:
617
After I comment out the following lines, the error is gone:
collisionLayer = map.layer['Collision']
collisionLayer.ccName = "map"
physics.addBody(collisionLayer, "static", { friction=0.5, bounce=0.3 } )
but the collision function does not get called.
Box2D collision detection is specified through the properties of a layer, tile, or object in an object layer. Ceramic adds physics automatically if the physics:enabled property is set to true.
Physics parameters are also set within properties. This:
physics.addBody(myObject, {friction = 0.5, bounce = 0.1})
Would correspond, in Tiled's properties, to this:
physics:friction = 0.5
physics:bounce = 0.1
For future people who are stuck in Collision Detection in Corona SDK with Tiled and Ceramic Tile Engine
In further testing, I found out that the issue of collision event not firing is I used a wrong set of collision events. The working collision events are :
local function onLocalCollision(self, event)
print("collision")
if event.phase == "began" then
print("Collision began")
elseif event.phase == "ended" then
print("Collision ended")
end
end
function onGlobalCollision(event)
if(event.phase == "began") then
print( "Global report: " .. event.object1.ccName .. " & " .. event.object2.ccName .. " collision began" )
elseif(event.phase == "ended") then
print( "Global report: " .. event.object1.ccName .. " & " .. event.object2.ccName .. " collision ended" )
end
print( "**** " .. event.element1 .. " -- " .. event.element2 )
end
function onPostCollision(event)
print("postCollision")
end
-- Local Collision
hero.collision = onLocalCollision
hero:addEventListener("collision", hero)
-- Global Collision
Runtime:addEventListener("collision", onGlobalCollision)
Runtime:addEventListener("postCollision", onPostCollision)
and each collision object has to have a name ( the property name ccName , you can pick any name you want , but it has to be set in Tiled's object list ).
Also, I removed the categoryBits and maskBits, seems they make the collision detection invalid.
Points to note:
Collision layer does not have to add to scene by programming ( it will be added automatically )
Only 1 set of collision detection methods ( Local / Global ) is needed ( but 2 sets can be run in parallel )
Turn off hybrid display mode when not needed, for better performance
It doesn't matter what the Layer format is ( Base64 / CSV works fine )
Remember to add physics:enabled in Collision Layer properties ( physics:friction and physics:bounce are optional , as per #CalebP's comment )

Images doesn´t appear in storyboard Corona SDK

I am doing a game in corona SDK, but I have this little problem.
I have a menu with a button. If I press it, it sends me to the first level of my game.
When I pass the final level, the game return me to the menu. Bur, if I start playing the first again, my images doesn´t appear.
The images are balls, and to pass the level, you have to eliminate all the balls. To do this, I use:
ball:removeSlef()
ball = nil
But, I don´t think that this is the problem, because I eliminate this lines, and it doesn´t work.
The images are create in scene:createScene function, and insert in the Group.
I short the code of the first level to be understood.
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local physics = require "physics"
physics.start(); physics.pause()
physics.setGravity( 0, 0 )
local cont = 0
local bur = {}
function eliminar1( event )
if (cont == 0) and (event.phase == "began") then
event.target:removeSelf()
bur[1] = nil
cont = cont + 1
end
end
function eliminar2( event )
if (cont == 1) and (event.phase == "began") then
bur[2]:removeSelf()
bur[2] = nil
cont = cont + 1
end
end
function eliminar3( event )
if (cont == 2) and (event.phase == "began") then
bur[3]:removeSelf()
bur[3] = nil
storyboard.gotoScene( "levels.1.level2" )
end
end
function scene:createScene ( event )
local screenGroup = self.view
for i = 1,3 do
bur[i] = display.newImage("irudiak/"..i..".png")
bur[i]:translate(math.random(0,280), math.random(0,400) )
physics.addBody( bur[i], {bounce = 0.3 } )
bur[i]:setLinearVelocity(math.random(-50,50), math.random(-50,50) )
screenGroup:insert(bur[i])
end
bur[1]:addEventListener("touch", eliminar1)
bur[2]:addEventListener("touch", eliminar2)
bur[3]:addEventListener("touch", eliminar3)
end
function scene:enterScene( event )
local screenGroup = self.view
physics.start()
end
function scene:exitScene( event )
local screenGroup = self.view
physics.stop()
end
function scene:destroyScene( event )
local screenGroup = self.view
package.loaded[physics] = nil
physics = nil
end
return scene
createScene is ran only first time when you gotoScene. Every next time only willEnterScene and enterScene are played. To play createScene again you have to remove it (storyboard.removeScene() I guess). Or you can move some stuff you need to willEnterScene. For more detailed info you can watch this: http://www.coronalabs.com/blog/2013/08/20/tutorial-reloading-storyboard-scenes/

Resources