0

我有个问题。根据下面的代码,我创建了一个对象 x 次(在本例中为 20 次)并添加到一个 ballGroup 中。此外,每个物体都应该有身体并对“碰撞”物理事件做出反应。但是所有创建的球都没有分配body属性(在将它们放入ballGroup之后)。所以我认为有一个问题(当我将球插入ballGroup时)。当我尝试将Body 添加到整个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
4

1 回答 1

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
于 2013-05-22T04:06:26.840 回答