I’m developing a top-down / RTS-style game in Castle Game Engine. I want the camera to automatically move (pan) when my player character approaches the edges of the viewport, similar to classic RTS games.
So far, I know how to move the player in the world, but I couldn’t find a built-in function or recommended approach to detect when the player is near the screen edges and move the camera smoothly.
Could you please advise on the best way to implement this? For example:
Should I convert the player’s world position to screen coordinates?
Or is there a frustum-based approach?
Any performance-friendly solution for multiple moving characters?
The most simple solution. You could simply decide how many tiles the player can move before the camera movement is required. It doesn’t have to be close to the edge. When player cross the threshold just change the camera position (X,Z) to the same as player.
Alternatively, you could have an invisible transform (an “observer”) that looks at the player, placed as a child of the camera. As the transform keep tracking the player, it changes its direction. You may decide than an angle of +/-30 degrees along X and Z axis, the camera should move.
Sorry for delayed answer. I’m very busy with some project.
To test it quickly I went the first route from my previous answer. Only “move to the right” is implemented here, and it’s recorded with standard Windows’ screen recorder.
In this example, inside Press function I just calculated the distance from Camera.Translation.X to the Box’s translation. When more than 500, I set (my own) variable “NeedCameraMove” to true.
Then in the Update I just do Camera1.Translation := Vector3(Camera1.Translation.X +Speed * SecondsPassed, …);
No math, no behaviors. I see no lag at all. If you experience a not-so-smooth movement, I guess it’s not related to the camera movement alone. Maybe it’d be better for your game if instead of moving all the way to the player’s position, you’d move just enough to keep the player visible. Less pixels to move inside the same timeframe.
Thank you for replying.
I think I’m having trouble because I have camera zoom and the camera is in Camera1.Orthographic mode.
I’ll try to fix it.
Thanks.
—————–update —————
I see. I’m currently calculating the edge in update, but I should calculate it in press.
I’ll get to it in a few hours and fix it.