【问题标题】:Setting x-position of objects in Corona using for loop使用 for 循环在 Corona 中设置对象的 x 位置
【发布时间】:2013-03-26 04:27:04
【问题描述】:

在我的游戏类中,我从另一个类(objA 和 objB)中调用两个对象,如下所示:

for i=1, countA do
pos.x = pos.x + 15
objA = objClass:new("objClass", group, pos)
wArray[i]=i
end

for j=1, countB do
pos.x = pos.x + xPoint
objB = objClass:new("objCLass", group, pos)
end

我需要 for 循环,因为我想在我的游戏类中添加这些对象的随机数。我的问题是,我想在我的游戏中同时定位 a 和 b。例如:objA - objA - objB - objB - objA 或 objB - objA - objB - objB。但是,鉴于我当前的代码,在添加所有 objB 对象之前,我最终得到的模式将是所有 objA 首先。

我知道简单的答案是只使用一个 for 循环,但我看到的问题是我的游戏中至少需要 1 个 objA 和 1 个 objB。我不能拥有所有 objB 或所有 objA。让他们随机定位的最佳方法是什么?提前致谢。

【问题讨论】:

    标签: lua coronasdk


    【解决方案1】:

    如果你想在 As 和 Bs 之间随机选择,你可以尝试类似

    local ab = {}
    
    for i = 1,countA+countB do
        ab[i] = i<=countA and "A" or "B"
    end
    
    for i = 1,countA+countB do
        local idx = math.random(#ab)
        local choice = table.remove(ab,idx)
    
        if choice=="A" then
            pos.x = pos.x + 15
            objA = objClass:new("objClass", group, pos)
        else
            pos.x = pos.x + xPoint
            objB = objClass:new("objClass", group, pos)
        end
    end
    

    【讨论】:

    • 太棒了!太感谢了。这是完美的。
    【解决方案2】:
    -- Prepare your counters (just an example)
    local countA = math.random(3)  -- 1,2,3
    local countB = math.random(5)  -- 1,2,3,4,5
    
    -- Generate permutation
    repeat
       if math.random(1-countB, countA) > 0 then 
          countA = countA - 1
          -- Do something with objA
       else
          countB = countB - 1
          -- Do something with objB
       end
    until countA + countB == 0
    

    【讨论】:

    • 非常感谢您的帮助。
    猜你喜欢
    • 2013-03-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    相关资源
    最近更新 更多