Zinggi / elm-2d-game / Game.TwoD.Camera

A camera to view the game world.

camera creation


type Camera

A camera represents how to render the virtual world. It's essentially a transformation from virtual game coordinates to pixel coordinates on the screen.

fixedArea : Basics.Float -> ( Basics.Float, Basics.Float ) -> Camera

A camera that always shows the same area. This is useful in a top down game. You probably want to specify the area as a multiplication of width and height:

fixedArea (16 * 10) ( x, y )

This means the camera will always show 160 square units of your game. In practice, this means that on a 16:10 viewport, 16 by 10 units of your game will be visible. But on a 4:3 viewport it would show 14.6 by 10.95 units. (sqrt(16_10_4/3)=14.6, sqrt(16_10_3/4)=10.95)

fixedWidth : Basics.Float -> ( Basics.Float, Basics.Float ) -> Camera

A camera that always shows width units of your game horizontally. Well suited for a side-scroller.

fixedHeight : Basics.Float -> ( Basics.Float, Basics.Float ) -> Camera

A camera that always shows height units of your game vertically. Well suited for a vertical scroller.

custom : (( Basics.Float, Basics.Float ) -> ( Basics.Float, Basics.Float )) -> ( Basics.Float, Basics.Float ) -> Camera

The custom camera allows you to use a function that maps viewport size (in pixel) to game units. E.g. here's an implementation of the fixedWidth camera using custom:

fixedWidth width =
    custom (\( w, h ) -> ( width, width * h / w ))

manipulate camera

getPosition : Camera -> ( Basics.Float, Basics.Float )

moveBy : ( Basics.Float, Basics.Float ) -> Camera -> Camera

Move a camera by the given vector relative to the camera.

moveTo : ( Basics.Float, Basics.Float ) -> Camera -> Camera

Move a camera to the given location. In absolute coordinates.

camera transformations

view : Camera -> ( Basics.Float, Basics.Float ) -> Math.Matrix4.Mat4

Gets the transformation that represents how to transform the camera back to the origin. The result of this is used in the vertex shader.

getViewSize : ( Basics.Float, Basics.Float ) -> Camera -> ( Basics.Float, Basics.Float )

Given the screen size, gets the width and height in game units

viewportToGameCoordinates : Camera -> ( Basics.Int, Basics.Int ) -> ( Basics.Int, Basics.Int ) -> ( Basics.Float, Basics.Float )

Convert coordinates on the canvas element to coordinates in the game. Coordinates on the canvas element are given relative to its top left corner.

viewportToGameCoordinates camera ( elementWidth, elementHeight ) ( positionX, positionY )

Element click coordinates can be extracted with a package like Elm-Canvas/ElementRelativeMouseEvents