碰撞事件和display.newGroup。如何将它们连接在一起?科罗纳

时间:2013-05-22 01:15:24

标签: lua corona

我有问题。根据下面的代码,我创建一个对象x次(在这种情况下为20次)并添加到ballGroup中。而且每一个物体都应该有身体并对“碰撞”物理事件做出反应。但是所有创建的球都没有赋予body属性(在将它们放入ballGroup之后)。所以我认为存在问题(当我将球插入ballGroup时)。当我尝试将addBody添加到整个ballGroup(带注释的行)时,只有最后一个球具有Body属性。知道如何解决这个问题吗?

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

1 个答案:

答案 0 :(得分:1)

每次打电话给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