Browse Source

Add drag and drop example;

bjorn 10 years ago
parent
commit
b09dd27fed
3 changed files with 55 additions and 2 deletions
  1. 14 1
      README.md
  2. 40 0
      main.lua
  3. 1 1
      rx-love.lua

+ 14 - 1
README.md

@@ -1,7 +1,20 @@
 RxLove
 RxLove
 ===
 ===
 
 
-Turn Love2D events into reactive streams. Requires [RxLua](https://github.com/bjornbytes/RxLua).
+Turn Love2D events into reactive streams:
+
+```lua
+require 'rx'
+require 'rx-love'
+
+love.keypressed
+  :filter(function(key) return key == ' ' end)
+  :subscribe(function()
+    print('You pressed the space bar')
+  end)
+```
+
+See [main.lua](main.lua) for another example. Requires [RxLua](https://github.com/bjornbytes/RxLua).
 See [Reactive Extensions](http://reactivex.io) for more info.
 See [Reactive Extensions](http://reactivex.io) for more info.
 
 
 License
 License

+ 40 - 0
main.lua

@@ -0,0 +1,40 @@
+local rx = require 'rx'
+require 'rx-love'
+
+-- This Subject keeps track of the x and y position of the circle.
+local object = rx.Subject.create(400, 300)
+
+local radius = 30
+local isLeft = function(x, y, button) return button == 'l' end
+
+-- Set up observables for clicking and releasing the left mouse button.
+local leftPressed = love.mousepressed:filter(isLeft)
+local leftReleased = love.mousereleased:filter(isLeft)
+
+-- Run some operations on the mousepressed and mousereleased observables:
+--  * filter out any mouse presses that aren't within the radius of the circle.
+--  * map over the mouse presses and return an observable from the love.mousemoved event, which
+--    produces the coordinates of the mouse as it moves.
+--  * takeUntil to stop moving the circle when the mouse is released.
+--  * flatten it to convert the observable of observables into an observable that just contains the
+--    mouse coordinates.
+--  * subscribe to them and set the circle's position.
+local drag = leftPressed
+  :filter(function(x, y)
+    local ox, oy = object:getValue()
+    return (x - ox) ^ 2 + (y - oy) ^ 2 < radius ^ 2
+  end)
+  :map(function()
+    return love.mousemoved:takeUntil(leftReleased)
+  end)
+  :flatten()
+  :subscribe(function(x, y)
+    object:onNext(x, y)
+  end)
+
+-- Subscribe to the love.draw event and draw the circle.
+love.draw:subscribe(function()
+  local x, y = object:getValue()
+  love.graphics.setColor(255, 255, 255)
+  love.graphics.circle('fill', x, y, radius)
+end)

+ 1 - 1
rx-love.lua

@@ -10,7 +10,7 @@ local events = {
   'keypressed',
   'keypressed',
   'keyreleased',
   'keyreleased',
   'mousefocus',
   'mousefocus',
-  'mousemove',
+  'mousemoved',
   'mousepressed',
   'mousepressed',
   'mousereleased',
   'mousereleased',
   'quit',
   'quit',