JustMuddles
JustMuddles

Reputation: 1

Handling Collision Events for multiple objects with physics

so I'm building a game with Corona (in lua) where there are multiple objects that include Physic attributes, and currently trying to store, manipulate them in a way where I can make collision handling easier... the idea is that no 2 out of the 3 objects collide.. the Objects being 1/ a Ball (of many that can be on the screen) 2/ the Table (that has some Physic attributes) and 3/ Pockets (Which end up just being some invisible rectangles)

out of 2 weeks of processing the mess I've come to this conclusion

a sample of the code structure create the 100 Balls

balls = {}
local i = 1
function createBalls ()
        for i = 1,100,1 do -- create the 100 and hide them?

        ball = display.newImage("ball.png")
        ball.isVisible = false
        ball.id = tostring( "ball " ..i )
        balls[#ball+1] = ball 
        sceneGroup:insert(ball[#ball])
    end
end

declare 6 pockets (using the id as the flag for collision handling)

local Pocket1 = display.newRect( screenWidth * .28, screenHeight * .5, 15, 18) --Left Pocket 60pts
physics.addBody( Pocket1, "kinematic", {isSensor = true})
Pocket1:addEventListener( "collision", Pocket1 ) Pocket1.isVisible = true Pocket1.alpha = 0.5
Pocket1.id ="Left Pocket 60pts"

local Pocket2 = display.newRect( screenWidth * .3945, screenHeight * .556, 15, 18) -- Left Pocket 30pts
physics.addBody( Pocket2, "kinematic", {isSensor = true} )
Pocket2:addEventListener( "collision", Pocket2 ) Pocket2.isVisible = false
Pocket2.id ="Left Pocket 30pts"

local Pocket3 = display.newRect( screenWidth * .512, screenHeight * .490, 15, 18) -- Center Pocket 10 pts
physics.addBody( Pocket3, "kinematic", {isSensor = true} )
Pocket3:addEventListener( "collision", Pocket3 ) Pocket3.isVisible = false
Pocket3.id ="Center Pocket 10pts"

local Pocket4 = display.newRect( screenWidth * .613, screenHeight * .556, 15, 18) -- Right Pocket 30 pts
physics.addBody( Pocket4, "kinematic", {isSensor = true} )
Pocket4:addEventListener( "collision", Pocket4 ) Pocket4.isVisible = false
Pocket4.id ="Right Pocket 30pts"

local Pocket5 = display.newRect( screenWidth * .736, screenHeight * .5, 15, 18) -- Far Right Pocket 60pts
physics.addBody( Pocket5, "kinematic", {isSensor = true} )
Pocket5:addEventListener( "collision", Pocket5 ) Pocket5.isVisible = false
Pocket5.id ="Right Pocket 60pts"

local Pocket6 = display.newRect( screenWidth * .512, screenHeight * .638, 50, 10) -- Kill-z Pocketphysics.addBody( Pocket6, "kinematic", {isSensor = true} )
Pocket6:addEventListener( "collision", Pocket6 ) Pocket6.isVisible = false
Pocket6.id ="Kill Pocket"

My problem, collision detection only works on the last ball that was loaded,

(in case anyone asks for the loader function)

--handle loader
function shootBall()
    createBalls() --obviously this will now spawn 100 balls

    if ballLoaded == true then 
    r1 = -687.5 r2 = -668
    r3 = 595 r4 = 645
    ball[k].x = screenWidth * .378 ball[k].y = screenHeight * .638
    ball[k]:scale(0.16,0.16)
    ball[k].isVisible = true
    physics.addBody( ball[k], "dynamic", {radius = 5.5, density=15.0, friction=0.8, bounce=0.0 } )
    ball[k]:setLinearVelocity( math.random(r1,r2), math.random(r3,r4))
    --and here it will have done nothing productive other than fill the screen with balls

    end

a Rollback Edit this was originally what would be called but as you can see isn't organised well at all, given the more recent code is a mess..

local i = 1
local balls  = {}

local function spawnBall()

    if i > 0 or  i < 100 then
     balls[i] = display.newImage("ball.png")
     balls[i].id = "ball "..i
     balls[i].x = screenWidth * .378
     balls[i].y = screenHeight * .638
     balls[i]:scale(0.16,0.16)
     balls[i].isVisible = true

     physics.addBody( balls[i], "dynamic", {radius = 5.5, density=15.0, friction=0.8, bounce=0.0 } )
     balls[i]:setLinearVelocity(math.random(-687.5,-668), math.random(595,645))
     sceneGroup:insert(balls[i])
     print(balls[i].id.. " shot")
    i = i + 1

    end

end`

Upvotes: 0

Views: 727

Answers (2)

JustMuddles
JustMuddles

Reputation: 1

So here is my solution, it's pretty comprehensive I can thank Danny from Corona Labs with most of the solution, passing parameters through a function was on the list but not particularly a priority, but Thanks for most of the work.

--on "Press" event
--Function to spawn an object
local function spawn(params)
    local ball = display.newImage(params.image)
    --Set the objects table to a table passed in by parameters
    ball.Table = params.Table
    --Automatically set the table index to be inserted into the next available table index
    ball.index = #ball.Table + 1
    --Give the object a custom name
    ball.id = "ball : " .. ball.index
    --If the object should have a body create it, else dont.
        if params.hasBody then
            --Allow physics parameters to be passed by parameters:
            ball.x = params.x or contentCenterX
            ball.y = params.y or contentCenterY
            ball.isVisible = params.isVisible or false
            ball.radius = params.radius or nil
            ball.density = params.density or 0
            ball.friction = params.friction or 0
            ball.bounce = params.bounce or 0
            ball.isSensor = params.isSensor or false
            ball.bodyType = params.bodyType or "dynamic"
            physics.addBody(ball, ball.bodyType, {radius = ball.radius, density = ball.density, friction = ball.friction, bounce = ball.bounce, isSensor = ball.isSensor})
            ball:setLinearVelocity(params.xVelocity or 0, params.yVelocity or 0)
            ball:scale(params.xScale or 1,params.yScale or 1)

        end
    --The objects group
    ball.group = params.group or nil
    --If the function call has a parameter named group then insert it into the specified group
    ball.group:insert(ball)
    --Insert the object into the table at the specified index
    ball.Table[ball.index] = ball       
    return ball
end
local displayGroup = display.newGroup()
--Create a table to hold balls
local ballTable = {}

--Create spawns
local function  ballSpawn()
    for i=1 ,1,1 do
        local spawns = spawn(

            {
            image = "ball.png",
            Table = ballTable,
            hasBody = true,
            x = screenWidth * .378,
            y = screenHeight * .638,
            isVisible = true,
            bodyType = "dynamic", radius = 5.5, density= 15.0, friction= 0.8, bounce = 0.0,
            xVelocity = math.random(-687.5,-678),
            yVelocity = math.random(595,645),
            xScale = 0.16, yScale = 0.16,
            group = sceneGroup,
            }
            )   
    end
end

This is the more atypical part of the code where I wanted to do a key by key test when ever a ball whether it was 3 or 5 or 25, if i=5 and ball: 3 collided with a test collision pocket I wanted to make sure that all collisions printed.

local function onPocketsCollision ( event)
local self = event.object2.id
local other = event.object1.id

    if event.phase == "began"  then

        for i = 1, #ballTable,1 do
            if (self == ballTable[i].id and other == Pocket1.id) then
                print(self .. " hit for " .. Pocket1.id)
                ballTable[i]:removeSelf()
                score.add(1)
            end
            if (self == ballTable[i].id and other == Pocket2.id) then
                print(self .. " hit for " .. Pocket2.id)
                ballTable[i]:removeSelf()
                score.add(1)
            end
            if (self == ballTable[i].id and other == Pocket3.id) then
                print(self .. " hit for " .. Pocket3.id)
                ballTable[i]:removeSelf()
                score.add(1)
            end
            if (self == ballTable[i].id and other == Pocket4.id) then
                print(self .. " hit for " .. Pocket4.id)
                ballTable[i]:removeSelf()
                score.add(1)
            end
            if (self == ballTable[i].id and other == Pocket5.id) then
                print(self .. " hit for " .. Pocket5.id)
                ballTable[i]:removeSelf()
                score.add(1)
            end
            if (self == ballTable[i].id and other == Pocket6.id) then
                print(self .. " hit " .. Pocket6.id)
                ballTable[i]:removeSelf()
                score.add(-1)
            end
        end
    end
end


Runtime:addEventListener( "collision", onPocketsCollision )

fantastically enough, it works great, it was just a case of reducing it down so it didn't look like crap... I'll be sure to take a little care in future when it comes to sharing code, must of been a poop line-by-line to read...

Upvotes: 0

Piglet
Piglet

Reputation: 28974

function createBalls ()
        for k = 1,100,1 do
        ball = {} -- we do this every loop cycle!!!
        ball[k] = display.newImage("ball.png")
        ball[k].isVisible = false
        ball[k].id = tostring( "ball " ..i )
        ball[#ball+1] = ball[k]
        sceneGroup:insert(ball[#ball])
    end
end

Here you re-define the global variable ball 100 times.

As you re-create ball every cycle #ball will always be 1. So you create a table, add various values to it at index k and 2, then recreate it again... So your global table ball is completely f***ed up.

In shootBall() you use index k which is not defined in the provided code...

Go through your code line by line and think about it. Use pen an paper and draw a table...

Please read something about the use of local variables in Lua!!!!

Upvotes: 0

Related Questions