The output of camera is rendered using a viewport. A viewport is simply a clipped rectangular section of the window. The global display object contains a default viewport which is the same size as the window. When we assign a camera to this viewport, the viewport will render whatever is in the camera's viewing range. Our scene may contain multiple cameras but only one can be assigned per viewport. Viewports may come in handy if you plan on using split screens or mini maps.
Let's look at the actual script that puts what we have discussed so far into action. The script allows you to move the camera around the scene and place sprite objects by pressing the mouse. The top part of the script initializes the scene and inserts a camera in it. Next, we have two callback functions. The first one translates the camera while the user is holding the right mouse button. The second callback function creates a new sprite and draws a circle on it whenever the user presses the left mouse button. The sprite is then inserted in the scene at world coordinates.
display:create ( "Camera example", 800, 600, 32, true ) camera = Camera ( ) scene = Layer ( ) scene:add_child ( camera ) display.viewport.camera = camera -- move the camera using the right button mouse.on_move = function ( mouse, dx, dy ) if mouse:is_down ( MBUTTON_RIGHT ) then camera.x = camera.x - dx camera.y = camera.y - dy end end -- draw a circle on left button click mouse.on_press = function ( mouse, button ) if button == MBUTTON_LEFT then local ptx, pty = camera:get_world_point ( mouse.xaxis, mouse.yaxis ) local s = Sprite ( ptx, pty ) s.canvas:circle ( 10 ) s.canvas:fill ( ) scene:add_child ( s ) end end
The neat part here is how the mouse cursor position (xaxis and yaxis) is converted to scene coords. Since the camera is assigned to the default viewport (which covers the entire window), the mouse cursor position can be treated as a point on the camera's coordinate system.