dragAndDrop.lua 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. local rx = require 'rx'
  2. require 'rx-love'
  3. -- This Subject keeps track of the x and y position of the circle.
  4. local object = rx.BehaviorSubject.create(400, 300)
  5. local radius = 30
  6. local isLeft = function(x, y, button) return button == 1 end
  7. -- Set up observables for clicking and releasing the left mouse button.
  8. local leftPressed = love.mousepressed:filter(isLeft)
  9. local leftReleased = love.mousereleased:filter(isLeft)
  10. -- Run some operations on the mousepressed and mousereleased observables:
  11. -- * filter out any mouse presses that aren't within the radius of the circle.
  12. -- * flatMap the mousepresses to start producing values from the love.mousemoved event. takeUntil
  13. -- ensures that the dragging stops when the mouse button is released.
  14. -- * subscribe to the mouse positions and set the circle's position accordingly.
  15. local drag = leftPressed
  16. :filter(function(x, y)
  17. local ox, oy = object:getValue()
  18. return (x - ox) ^ 2 + (y - oy) ^ 2 < radius ^ 2
  19. end)
  20. :flatMap(function()
  21. return love.mousemoved:takeUntil(leftReleased)
  22. end)
  23. :subscribe(function(x, y)
  24. object:onNext(x, y)
  25. end)
  26. -- Subscribe to the love.draw event and draw the circle.
  27. love.draw:subscribe(function()
  28. local x, y = object:getValue()
  29. love.graphics.setColor(255, 0, 0)
  30. love.graphics.circle('fill', x, y, radius)
  31. love.graphics.circle('line', x, y, radius)
  32. end)