Giter Site home page Giter Site logo

gamera's Introduction

gamera.lua

A camera for LÖVE.

Initial setup

The first thing one needs to do to use gamera is to create it. You do so with gamera.new. This function requires 4 numbers (left, top, width and height) defining the "world boundaries" for the camera.

local cam = gamera.new(0,0,2000,2000)

The left and top parameters are usually 0,0, but they can be anything, even negative numbers (see below).

You can update the world definition later on with setWorld:

cam:setWorld(0,0,2000,2000)

By default gamera will use the whole screen to display graphics. You can restrict the amount of screen used with setWindow:

cam:setWindow(0,0,800,600)

Moving the camera around

You can move the camera around by using setPosition:

cam:setPosition(100, 200)

setPosition takes into account the current window boundaries and world boundaries, and will keep the view inside the world. This means that if you try to look at something very close to the left border of the world, for example, the camera will not "scroll" to show empty space.

You can also zoom in and zoom out. This is done using the setScale method. It's got a single parameter, which is used for increasing and decreasing the height and width. The default scale is 1.0.

cam:setScale(2.0) -- make everything twice as bigger. By default, scale is 1 (no change)

Take notice that gamera limits the amount of zoom out you can make; you can not "zoom out" to see the world edges. If you want to do this, make the world bigger first. For example, to give a 100-pixels border to a world defined as 0,0,2000,, you can define it like -100,100,2100,2100 instead.

Finally, you can modify the angle with setAngle:

cam:setAngle(newAngle) -- newAngle is in radians, by default the angle is 0

setAngle will change both the scale and position of the camera to force you not to see the world borders. If you don't want this to happen, expand the world borders as mentioned above.

Drawing

The camera has one method called "draw". It takes one function as a parameter. Here's one example:

local function drawCameraStuff(l,t,w,h)
  -- draw stuff that will be affected by the camera, for example:
  drawBackground(l,t,w,h)
  drawTiles(l,t,w,h)
  drawEntities(l,t,w,h)
end

...

-- pass your custom function to cam:draw when you want to draw stuff
cam:draw(drawCameraStuff)

Alternatively, you could create a custom anonymous function and pass it to cam:draw, but in some extreme cases this could have a non-negligible performance impact.

cam:draw(function(l,t,w,h)
  -- draw camera stuff here
end)

Anything drawn inside the custom function you pass to cam:draw be modified by the camera (scaled, rotated, translated and cut) so that it appears as it should in the screen window.

Notice that the function takes 4 optional parameters. These parameters represent the area that the camera "sees" (same as calling cam:getVisible()). They can be used to optimize the drawing, and not draw anything outside of those borders. Those borders are always axis-aligned. This means that when the camera is rotated, the area might include elements that are not strictly visible.

Querying the camera

  • cam:getWorld() returns the l,t,w,h of the world

  • cam:getWindow() returns the l,t,w,h of the screen window

  • cam:getVisible() returns the l,t,w,h of what is currently visible in the world, taking into account rotation, scale and translation. It coincides with the parameters of the callback function in gamera.draw. It can contain more than what is necessary due to rotation.

  • cam:getVisibleCorners() returns the corners of the rotated rectangle that represent the exact region being seen by the camera, in the form x1,y1,x2,y2,x3,y3,x4,y4

  • cam:getPosition() returns the coordinates the camera is currently "looking at", after it has been corrected so that the world boundaries are not visible, if possible.

  • cam:getScale() returns the current scaleX and scaleY parameters

  • cam:getAngle() returns the current rotation angle, in radians

Coordinate transformations

  • cam:toWorld(x,y) transforms screen coordinates into world coordinates, taking into account the window, scale, rotation and translation. Useful for mouse interaction, for example.
  • cam:toScreen(x,y) transforms given a coordinate in the world, return the real coords it has on the screen. Useul to represent icons in minimaps, for example.

FAQ

Everything looks kindof "blurry" when I do zooms/rotations with this library. How do I prevent it?

LÖVE uses a default filter mode which makes images "blurry" when you make almost any transformation to them. To deactivate this behavior globally, you can add this at the beginning of your game, before you load anything (for example at the beginning of love.load):

love.graphics.setDefaultFilter( 'nearest', 'nearest' )

You can also set the filter of each image you load individually:

local img = love.graphics.newImage('imgs/player.png')
img:setFilter('nearest', 'nearest')

I see "seams" around my tiles when I use this library. Why?

It is due to a combination of factors: how OpenGL textures work, how floating point numbers work and how LÖVE stores texture information in memory.

The end result is that sometimes, when drawing an image, "parts of the area around it" are also drawn. So if you draw a Quad of "earth", and immediately above it in your image you have a "bright lava" tile, when you draw the earth tile sometimes "a bit of the lava" is drawn near the top. If you are using images instead of quads, you can get seams too (either black or from other colors, depending on how the image is stored in memory).

To prevent this:

  • Always use quads for tiles, never images.
  • Add a 2-pixel border to each of your quads (So for a 32x32 quad, you use 36x36 space, with the 32x32 quad in the center and a 2-pixel border)
  • Fill up the borders with the colors of the 32x32 quad. For example, if the earth quad is all brown on its left side, color the left border brown. If on its upper side is gray in the center and brown on the sides, color the upper border gray in the center and brown on the sides.
  • The quads will still be 32x32 - they will just have some border in the image now.
  • The "seams" will still appear, but now they will show the "colored borders" of the quads, so they will not be noticeable.
  • Calculating the coordinates of the quads is a bit more complex than before. You can use anim8's "Grids" to simplify getting them:
local anim8 = require 'anim8'

...

local tiles = love.graphics.newImage('tiles.png')
local w,h = tiles:getDimensions()

local g = anim8.newGrid(32, 32, w, h, 0, 0, 2) -- tileWidth, tileHeight, imageW, imageH, left, top, border

local earth = g(1,1)[1] -- Get the first column, first row 32x32 quad, including border
local water = g(2,1)[1] -- Get the second column, first row quad

You can combine this with the previous FAQ and use a "nearest" filter instead of a linear one.

The camera is "clamping". I don't want it to clamp

Yes, by default gamera cameras make sure that they always "stay in the world". They never "show black borders" around the scene.

There is no way to deactivate this behaviour. However, you can "mimic" it very well. It's actually very simple: give the camera a bigger world.

For example, if instead of doing this:

local cam = gamera.new(0,0,2000,2000)

You do this:

local cam = gamera.new(-200,-200,2200,2200)

You will give the world a 200 pixel "black border" which will be visible when the camera zooms out or moves to the left or right.

If you want to display the borders only sometimes, you can use setWorld to activate/deactivate the zoom:

local cam = gamera.new(0,0,2000,2000)

... -- the camera "clamps" when drawing

cam:setWorld(-200,-200,2200,2200)

... -- Now the camera has a 200px border

cam:setWorld(0,0,2000,2000)

... -- now it clamps again

Installation

Just copy the gamera.lua file wherever you want it. Then require it where you need it:

local gamera = require 'gamera'

Please make sure that you read the license, too (for your convenience it's included at the beginning of the gamera.lua file).

gamera's People

Contributors

giraugh avatar kikito avatar ulydev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gamera's Issues

black borders

I am using a tile map as the game map and load it with STI.

The tile map has tiles of 16x16 and the full size is 512x512 (the game world).

I then have a resolution of 768 x 672 for my game window.

The player is located at some location on the map.

Considering I am using a higher resolution (768 x 672), if I were to not touch any scaling
options, the game would be bad because the full map is shown then, that's not what I
want. So, I adjusted a scale of 3, which makes good zoom for my game.

Now using Gamera, I set the cam to my player initial position and that is fine.

If I scroll up or left, the Gamera detects the world boundaries and it doesn't show
the black borders. But.... it doesn't seem to work for right and down, it shows black
borders there. How can I make it stop scrolling considering the scale of 3 and all
the dimensions above? I don't want to see the black borders to the right and down.

Thank you!

[bug]cam:setPosition does not work in huge world

I absolutely love this library, and I don't think my game will work without it, but I am encountering a problem.

The camera's creation line is as such:
local cam = gamera.new(-700000,-700000,700000,700000)

but when drawing:

  --cam:setScale(.25)
  cam:setPosition(charx*4,chary*4)
  --cam:setAngle(charr)
  
  
  
cam:draw(function(l,t,w,h)
  
  love.graphics.draw(stat, 200, 200, 0, .3, .3, stat:getWidth()*.5, stat:getHeight()*.5)
  love.graphics.draw(char,charx,chary,charr, .3, .3, char:getWidth()*.5, char:getHeight()*.5)
  
  end)

cam:setPosition does not set the position to the character's location, instead the location stays at (-400, -300)

The character is moving to its own position, so I know it isn't a problem with my code, please help.

Problem with setPosition

i need help with this:

--init
local active_camera = Gamera.new(0, 0, 1024, 512)

--in draw
local screen_x, screen_y, screen_w, screen_h = active_camera:getWindow()
local world_x, world_y, world_w, world_h = active_camera:getWorld()
local dx = Imgui.SliderInt("x", screen_x, 0, world_w)
local dy = Imgui.SliderInt("y", screen_y, 0, world_h)
print(dx, dy) --works
active_camera:setPosition(dx, dy)
print(active_camera:getWindow()) --should be updated, but prints 0, 0, 1024, 512 still

the position value of the window should change, but it returns to 0 :/

setPosition changes the x and y position of the Window (subset of World), but it resets to 0

ive tried

active_camera.x = dx
active_camera.y = dy

but instead of resetting to 0, it resets to 512 (half of 1024), because internally gamera computes position and width since (0,0) in camera coordinates is center

Sent from my HUAWEI GR5 2017 using FastHub

Handling screen size changes?

Shouldn't there be like a cam:resize(w, h) method to be called in love.resize for screen size changes?

This specifically applies to Android I'd say because I notice that in love.load I have a smaller size given and then right after love.resize is called with the correct size, but since most games and all prefer initialization in love.load the end result is everything is working with smaller screen size than actually is. Would be good to have a function to just call in the resize method and keep everything updated.

Support gravity and crop/fill for aspect mismatches

Gamera looks pretty great! But there's a use case it doesn't cover that I need, namely being able to specify a camera view based on any arbitrary aspect and having the screen preferentially cover a particular area of it. For example, the incredibly tedious scaling setup code in one of my games sets the screen up to prevent people from peeking ahead, and there's also obvious use cases for cropping the camera's view in case of a mismatch instead.

I would propose that there be an optional configuration stash that gets passed in as a fifth parameter, with options like:

gamera.new(0, 0, 100, 100, {
    fit = 'grow',
    anchor = {0.5, 1}
})

where fit can be one of (for example) grow, shrink, or stretch, and anchor would give the relative anchor point for the center (defaulting to {0.5,0.5}); so for example the above would crop the camera view to match the aspect with the center point being the center of the bottom edge; on a 16:9 screen your screen coordinates would map to (0,43.75)–(100,100), for example.

As another example, the camera setup for the code I linked to would be:

gamera.new(-960, -540, 1920, 1080, { fit = 'shrink', anchor = {0.5, 1} });

Floor camera coordinates?

I noticed that sometimes black seems occured between tiles when using STI. Usually flooring all coordinates fixes that, but at a large zoom (I am using x4) that produces very laggy and noticeable bad camer movement, so simply flooring the values is not enough, they need to be floored at zoom-level precision. Here is how I patched gamera for my purposes:
(optionally?) allow subpixel camera movement

function gamera:draw(f)
  love.graphics.setScissor(self:getWindow())

  love.graphics.push()
    local scale = self.scale
    love.graphics.scale(scale)

    local tx, ty = math.floor(self.w2 + self.l, self.h2 + self.t)
    love.graphics.translate(tx/scale, ty/scale)
    love.graphics.rotate(-self.angle)
    tx, ty = math.floor(-self.x*scale, -self.y*scale)
    love.graphics.translate(tx/scale, ty/scale)

    f(self:getVisible())

  love.graphics.pop()

  love.graphics.setScissor()
end

the code is messy, but it should be understandable; every coordinate used is first multiplied by scale, then floored and divided by scale again. Note that my math.floor can floor multiple values, the default doesn't.

[BUG-NOTBUG-UNSURE] Smooth camera movement

Hello,

I'm not sure how to achieve a smooth camera movement. I'm not sure if it is a bug or not, so if this not the right place to ask feel free to point me to a better place, maybe love2d forum, a discord channel or what could fits better.

This is some strip down version of my code, if it's not enough I can provide more code/context.

What I would love to achieve:
Display a portion of a top down map that smoothly follow the player

So let's start from the initial setup

local MAP = nil

local PLAYER = {
    speed = 48,
    x = 0,
    y = 0
}

local CAM = gamera.new(0, 0, MAP_WIDTH * TILE_SIZE, MAP_HEIGHT * TILE_SIZE)
CAM:setWindow(0, 0, TILE_SIZE * TILES_RENDERED, TILE_SIZE * TILES_RENDERED)
CAM:setPosition(0, 0)

in love.update i take care of updating the player position

function love.update(dt)
    if love.keyboard.isDown('w') then
        PLAYER.y = PLAYER.y - PLAYER.speed * dt
    end

    if love.keyboard.isDown('s') then
        PLAYER.y = PLAYER.y + PLAYER.speed * dt
    end

    if love.keyboard.isDown('a') then
        PLAYER.x = PLAYER.x - PLAYER.speed * dt
    end

    if love.keyboard.isDown('d') then
        PLAYER.x = PLAYER.x + PLAYER.speed * dt
    end

    -- here's my struggle
    CAM:setPosition(math.ceil(PLAYER.x / TILE_SIZE) * TILE_SIZE, math.ceil(PLAYER.y / TILE_SIZE) * TILE_SIZE)

gamera:draw function within love.draw

        CAM:draw(
            function(l, t, w, h)
                local minX = l / TILE_SIZE
                local maxX = clamp(minX, minX + TILES_RENDERED, #MAP)
                local minY = t / TILE_SIZE
                local maxY = clamp(minY, minY + TILES_RENDERED, #MAP)
                for x = minX, maxX do
                    for y = maxY, minY, -1 do
                       print(PLAYER.x, PLAYER.y, l, t) -- see [EDIT]
                        love.graphics.setColor(1, 1, 1, 1)
                        if MAP[x + 1][y + 1] < GROUND_THRESHOLD then
                            love.graphics.draw(TT, T[3], x * TILE_SIZE, y * TILE_SIZE)
                        else
                            love.graphics.draw(TT, T[32], x * TILE_SIZE, y * TILE_SIZE)
                        end
                    end
                end
            end
        )

Now the first question: since I want the camera to follow the player, should i call gamera:setPosition in love.update?
CAM:setPosition(math.ceil(PLAYER.x / TILE_SIZE) * TILE_SIZE, math.ceil(PLAYER.y / TILE_SIZE) * TILE_SIZE) makes the transition of the camera not smooth (I'm really losing my mind, I think this is expected because I transform player position into tile x,y), and I can't figure out how I could achieve it.

[EDIT]
If I simply CAM:setPosition(PLAYER.x, PLAYER.y) after a certain value, the l and t parametrs of CAM:draw turn out to be float so that MAP[x + 1][y + 1] evaluate to nil < GROUND_THRESHOLD and then crash

Output
print(PLAYER.x, PLAYER.y, l, t)
inside the inner for loop check CAM:draw snippet before
0       272.52557759732 0       16.52557759732
Error: main.lua:144: attempt to compare nil with number
stack traceback:
        [string "boot.lua"]:777: in function '__lt'
        main.lua:144: in function 'f'
        gamera.lua:195: in function 'draw'
        main.lua:134: in function 'draw'
        [string "boot.lua"]:618: in function <[string "boot.lua"]:594>
        [C]: in function 'xpcall'

[/EDIT]

Thanks in advance

[bug] clamp in adjustPosition lead camera con't change it position !

I just use below code in my game:
cam = gamera.new(0,0, 800,600) cam:setPosition(100, 100)

but I debug it found in "gamera:draw" in line 181 which 'self.x self.y' always 300 and 400.
it made me crazy untill I delete line 62 in local function "clamp" 🎅 , then, everything is ok

However, It isn't a long - term policy.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.