How do I properly move and zoom the camera?

Hey!

I’ve tried to modify the camera, to make it zoom in and center onto a tileset.
I can’t quite get it right, and I’m not sure what I’m missing.

I haven’t added code to make it handle various aspect ratios yet, but I expected this code to stretch the tileset over the entire screen.

What am I missing?

rendering.render_script

local x, y, w, h

function update(self)
    [...]
    --render.set_viewport(0, 0, render.get_window_width(), render.get_window_height())
    render.set_viewport(self.x,self.y,self.w,self.h)
    [...]
end

function on_message(self, message_id, message)
    [...]
    elseif message_id == hash("set_viewport") then
        adjust_camera_after_tiles(self, message)
    end
    [...]
end

function adjust_camera_after_tiles(self, rect)
	self.x = rect.x
	self.y = rect.y
	self.w = rect.w
	self.h = rect.h
end

level_spawner.script

-- Set up camera properly
local bx,by,bw,bh = tilemap.get_bounds("#tilemap")
	
bx = bx * level_data.TILE_SIZE
by = by * level_data.TILE_SIZE
bw = bw * level_data.TILE_SIZE
bh = bh * level_data.TILE_SIZE

msg.post("@render:", "set_viewport", { x=bx,y=by,w=bw,h=bh} )

Hi,

You need to set the projection and keep the viewport as is. The following will, for instance, draw into a 100x100 square in the window, independent of the projection:

render.set_viewport(0, 0, 100, 100)

And the following renders from the view matrix center (set in render.set_view()) with orthographic projection 32 units in each direction, i.e. a 64x64 square. It will be drawn into the set viewport:

render.set_projection(vmath.matrix4_orthographic(-32, 32, -32, 32, -1000, 1000))

Thanks, seems to work!

I suggest implementing a more intuitive camera interface - usually you’ll want to be able to either set its position, rotate it, or zoom it, but very rarely actually modify its projection matrix.

Yes, the camera definitely needs to be looked at at some point. You can rotate and move it though. Just apply the transformations you need to the game object that holds the camera component.

I didn’t know there was such a thing!
Where do I find it? I couldn’t see it in the scene

1 Like

Just create a new camera file and attach the component to a game object. Note that the default FOV is currently set to 45 degrees. It should be expressed in radians.