Search code examples
c#game-developmentgodotgdscript

Camera controller with fly mode in Godot


I'm working on a little project in Godot with Procedural Terrain generation.
I need a really basic Camera controller that instead of jumping can fly. Even the Fps controller from the Godot official's Fps Tutorial is overkilled for my needs. I'm quite new to Godot and GDScript, and even if I know well C#, I don't know hot to move in Godot with it (I prefer GDScript in Godot because of the lack of an internal editor for C#).
Can anyone please help me? Thanks


Solution

  • For testing purposes, my go to is "Simple Free-Look Camera" by adamviola, you can find it on the asset library. When you download it, it will give you a camera.gd script that you can attach to a Camera in your scene (dragging the file from the File System panel to the Scene panel will do). Make the current of the Camera is set true. And that is all it takes.

    The script mimics the basic movement of the editor camera, so you press right click to look around and WASD to fly. Q and E move vertically. And you can use the mouse wheel to change the fly speed.

    Also, just like everything in the asset library it is gratis (which is why it is not an asset store). Also it is open source. So you can open it and study the code. And also it is libre, so you are also free to modify however you want. The above description of the controls should also help as starting point for what to look for in the code.


    What follows is a short explanation of what the code of camera.gd does.

    You can find in the code that it uses Input.set_mouse_mode to capture the mouse when you press right click. And it will store the relative motion when it gets a InputEventMouseMotion (this is in _input by the way) for later rotating the Camera using a combination of rotate_y and rotate_object_local (that part is in _update_mouselook). Horizontal mouse motion is translated to yaw, and vertical mouse motion is translated to pitch, the code also clamps the pitch.

    It will also keep track of the state of the keys it is interested in. You can find the variables _w, _s, _a, _d, _q, _e on the top of the script, and updated on _input when it gets a InputEventKey. The state of those keys is used to compute a direction vector - on which it applies velocity and acceleration - and finally move the Camera with translate (you can find that on _update_movement). Note that translate is affected by the orientation of the Camera, so the z axis is where you are looking at.

    The mouse wheel input is also taken on _input, and it updates a velocity multiplier which is applied in _update_movement.