How to get the position of a moving object once? without it being updated

232 Views Asked by At

I have an object moving "freely" with body:applyForce( x, y ).

I want to track it's previous position.

I set a timer and with every second that goes by i get the position of the moving object, the problem is the position keeps updating to the object's current position. that's not what i want. I want it's position one second ago.

I have like 10 ideas on how to do what i want to do, i just think there has to be a simpler and easier way.

the closest i got was a small if statement that inserts the position into a table but again the problem is that the position keeps updating to the current position not the previous one.

object = {}
object.x = 250
object.y = 200
object.body = love.physics.newBody(world, object.x, object.y, 'dynamic')
object.shape = love.physics.newCircleShape(5)
object.fixture = love.physics.newFixture(object.body, object.shape, 1)
--
object.body:applyForce( 5, 0 )
-- the object is moving to the right, on the x-axis

what i want is to track it's position while it's traveling. something like

function objectTracking()
   timer = timer + dt
   --
   if timer == 0 then
       varPreviousPositionX = object.body:getX()
       varPreviousPositionY = object.body:getY()
   elseif timer == 1 then
       timer = 0
   end
end

that doesn't work. just wanted to write something quick to help you see the problem.

1

There are 1 best solutions below

2
Ivan On

Your initial idea is good, you can indeed perform something like that to cache the previous position, to be used in the next loop iteration.

I am not sure why you are involving the timer, as adding dt to timer might give a result other than 0 or 1, (assuming dt is deltatime, which usually results in a number lower than 1 and higher than 0).

The following code will work as expected:

local varPreviousPositionX
local varPreviousPositionY

local function objectTracking()
  if varPreviousPositionX and varPreviousPositionY then
    -- do something with it
  end

  -- move body

  varPreviousPositionX = object.body:getX()
  varPreviousPositionY = object.body:getY()
end