[Solved]Using a timer to iterate through a table

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
ac3raven
Citizen
Posts: 60
Joined: Tue May 19, 2009 1:14 am

[Solved]Using a timer to iterate through a table

Post by ac3raven »

I have a player table. Inside that player table is multiple "horse" tables.

The horses are lined up by offsetting their x position based on the x of the previously added horse.

When the player jumps, I need the lead horses to jump in sequence from the lead horse to the last horse, such that the arc of the jump is like a wave.

It seems like hump.timer would be useful for this. I just don't know how to use it in my code, and could use some help.

I've added some comments to the below code for context.

Code: Select all

function horseadd()
  local horse = {
    img = player.img, 
    x = FrameWidth/2+FrameWidth/3.5, 
    y = 100, 
    yspeed = 0,
    jumpStrength = 325,
    onGround = true,
    jumptimer = 0, --the first horse jumps instantly
    offset = 45
    }
  if #player > 0 then
    local prevHorse = player[#player]
    horse.x = prevHorse.x + horse.offset
    horse.jumptimer = prevHorse.jumptimer + 0.1 --each subsequent horse jumps at a delay realtive to the horse in front of it.
  end
  table.insert(player,horse)
end



function love.update(dt)
  for i,v in ipairs(player) do
    Timer.every(v.jumptimer,jump(v)) --hump.timer function that I'm certainly not using correctly
    v.y = v.y + v.yspeed * dt
    v.yspeed = v.yspeed + grav
    if CheckCollisionBox(
      v.x,v.y,player.w,player.h,
      ground.x,ground.y,ground.w,ground.h) 
    then
      v.yspeed = 0
      v.y = ground.y - player.h
      v.onGround = true
    end
  end
end



function love.keypressed(key)
  if key == "z" then
    --player[1].yspeed = player[1].yspeed - player[1].jumpStrength
    for i,v in ipairs(player) do
      jump(player[i])
    end
  end
end



function jump(horse)
  if horse.onGround then
    horse.yspeed = horse.yspeed - horse.jumpStrength
    horse.onGround = false
  end
end
Last edited by ac3raven on Sat Jun 16, 2018 4:39 am, edited 1 time in total.
User avatar
ac3raven
Citizen
Posts: 60
Joined: Tue May 19, 2009 1:14 am

Re: Using a timer to iterate through a table

Post by ac3raven »

Okay, well I figured out. So here is the solution. I was using the wrong timer function, mainly.

First, I added Timer.update(dt) to love.update.

Then I changed my keypressed function to look like this:

Code: Select all

function love.keypressed(key)
  if key == "z" then
    for i,v in ipairs(player) do
      Timer.after(player[i].jumptimer,function()jump(player[i])end)
    end
  end
end
Post Reply

Who is online

Users browsing this forum: No registered users and 42 guests