Page 1 of 1

Object does not stop correctly

Posted: Sat Dec 19, 2020 8:25 am
by Soul_Investor
I fallowed a tutorial where you create a button.

When you click it, it will teleport to a random position and you get a +1 to score.

I was thinking instead of teleporting I can make the button move to a new random x position when clicked.

I do not understand what I am doing wrong because as soon as the button reaches the destination it swings left and right trying to find

that 0 difference betwenn mouse potion and button position

Looking for a better understanding of this.

Please check the love file and the code comments.

Code: Select all

function love.load()

  --Create Button object with properties
  button = {}
  button.x = 100
  button.y = 100
  button.size = 50

  -- Set the Target where the Button should move in X direction to button x position so it does nothing at first
  targetX = button.x
  score = 0

  speed = 400

  myFont = love.graphics.newFont(40)
end

Code: Select all

function love.update(dt)
  move(dt) --Call move every 60 frames
end

Code: Select all

function love.draw()

  love.graphics.setColor(1, 0, 0)
  love.graphics.circle('fill', button.x, button.y, button.size)

  love.graphics.setFont(myFont)
  love.graphics.setColor(1, 1, 1)
  love.graphics.print(score)

end

Code: Select all

function love.mousepressed(mouseX, mouseY, clickType, isTouch)

  if clickType == 1 then
  
    --I wanted to check if the mouse position is inside the Button (I know there is a formula you can use but wanted to try this way).
    --The way I calculate its more like checing a rectangle and is not precise diagonaly where the curb of the circle is
    
    if (mouseX > button.x-button.size and mouseX < button.x+button.size) and (mouseY > button.y-button.size and mouseY < button.y+button.size) then
    
      score = score + 1
      
      --After each press on Button set a new target on X Axes for the Button to move
      targetX = love.math.random(50,300)
      
    end
  end

end

Code: Select all

function move (dt)

  --Checked if the Button X position is bigger or smaller than targetX and ajust the speed to positive or negative
  
  if (button.x - targetX) > 0 then
    button.x = button.x - speed * dt
  elseif (button.x - targetX) < 0 then
    button.x = button.x + speed * dt
  else
    button.x = button.x
  end

end

Re: Object does not stop correctly

Posted: Mon Dec 21, 2020 8:08 am
by HDPLocust
This is because your button in the last frame jumps over the target destination, never reaching it and trying to go back.
Try this:

Code: Select all

function move (dt)
  --Checked if the Button X position is bigger or smaller than targetX and ajust the speed to positive or negative
  if button.x > targetX then
    button.x = math.max(button.x - speed * dt, targetX)
  elseif button.x < targetX then
    button.x = math.min(button.x + speed * dt, targetX)
  end
end