Pascu2001
Pascu2001

Reputation: 11

Game moves faster after weird interaction

Im trying to make a game in love2d using Lua where you control some humans and order them to do certain tasks (get Wood, fight etc). The game is supposed to start with 1 human, then add more using resources. The problem is, after I tried adding more using space button to see how they interact, they move faster the more humans I add. Here is the code for spawning, walking and updating:

function spawnPeople(x, y)
    local people = world:newRectangleCollider(x, y, 70, 90, {collision_class = 'Player'})
    table.insert(peopleS, people)    

    people:setFixedRotation(true)

    people.direction = d[math.random(1,2)]
    people.speed = 20
end

function walk(dt)
    for i,p in ipairs(peopleS) do

        local px, py = p:getPosition()
            p:setX(px + p.speed * p.direction * dt)

        if IsTimeToProcess(math.random(2)) then
            p.direction = d[math.random(2)]
            p.speed = s[math.random(2)]
        end
        
    end
end

function updatePeople(dt)
    for i,p in ipairs(peopleS) do
        local px, py = p:getPosition()

        local colliders = world:queryRectangleArea(px +(40 * p.direction), py + 40, 10, 10)

        walk(dt)
    end
end

I tried printing the speed to see if they stack and the value is unchanged no matter how many humans I add, even tho the game moves faster. Made people.speed into a global variable, nothing. Why is that? Whats going on?

Upvotes: 1

Views: 50

Answers (1)

Luatic
Luatic

Reputation: 11191

Your walk(dt) function loops over all people, moving them all. You call this function for every person. This means that the more people there are, the more calls the your walk(dt), the larger the distance walked. Just move walk(dt) out of the loop:

function updatePeople(dt)
    for i,p in ipairs(peopleS) do
        local px, py = p:getPosition()

        local colliders = world:queryRectangleArea(px +(40 * p.direction), py + 40, 10, 10)
        -- colliders etc. currently unused, but I assume you'll use them later?  
    end
    walk(dt)
end

You could refactor your walk function to not move all people, but rather only a single entity p. Then you could call walk(p, dt) inside the loop. You'd have to get rid of the loop in walk then.

Upvotes: 1

Related Questions