[SOLVED] Clamping camera Position when following player

Hey all, I’m a little new to Defold and somewhat new to game dev.

Here’s what I’m trying to do:
I’ve got an orthographic camera following a 2D player character. I’d like to clamp the x position of the camera as the player reaches the beginning and end of the tilemap. So as a player reaches the end of the map, they’ll also move closer to the right-hand side of the camera and visa-versa.

I’ve got the camera position clamping between the start and end of the map. So I think I need to somehow get the in-game pixel width of the camera view, divide that in half and use it as an offset of the min/max clamp values.

So my question is: how can I get the number of in-game pixels currently visible through a camera along the x axis?

Thanks and I hope this makes sense.

(also note that I’m not looking for something like render.get_window_width().

Assuming you’re using the built-in camera component, and not zooming the camera in or out, I would just do something like this in an init() function:

local width = tonumber(sys.get_config("display.width"))
self.offset = width / 2

Hey @pranavraja, thanks so much for taking the time to look at this. I actually did need handle zooming… I didn’t even think to make that part of my question. But I seem to have found a solution. I ended up coming across the Defold Orthographic camera, which had some methods that sounded promising, so I installed it. I’m now getting the width of the viewable area within the camera by calling camera.screen_to_world_bounds, then subtracting the x coord from the z coord of its return value, then tacking that value on to both ends of a clamp function. So far it seems to be working well enough for my needs.

Thanks again

2 Likes

Orthographic also has a built-in camera.bounds() function which I think is what you’re trying to implement?

4 Likes

Ha, wonderful suggestion @Potota. I’m embarrassed that I didn’t see this. But it’s working perfectly and so much cleaner that what I had.