Last active
May 19, 2022 13:58
-
-
Save Michael-Sjogren/87a95b865164feb6f903cc2fb0acd994 to your computer and use it in GitHub Desktop.
A 3D Starter First Person look & movement script for Godot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends KinematicBody | |
export(NodePath) var cam_path | |
const MOVE_SPEED = 5.0 | |
const MOUSE_SENSITIVITY = 0.0010 | |
var _camera:Camera | |
var _player_input:Vector3 | |
var _velocity:Vector3 | |
func _ready(): | |
_camera = get_node(cam_path) | |
assert(_camera) | |
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) | |
func _physics_process(delta:float): | |
_move(delta) | |
func _unhandled_input(event): | |
_player_input = Vector3( | |
Input.get_axis("move_left","move_right"), | |
0, | |
Input.get_axis("move_forward","move_backward") | |
).normalized() | |
if event is InputEventMouseMotion: | |
_head_look(-event.relative) | |
func get_move_direction() -> Vector3: | |
return (_camera.global_transform.basis * _player_input).normalized() | |
func _move(delta:float) -> void: | |
var dir = get_move_direction() | |
var new_vel:Vector3 = dir * MOVE_SPEED | |
_velocity.y += -9.8 * delta | |
new_vel.y = _velocity.y | |
_velocity = new_vel | |
_velocity = move_and_slide(_velocity,Vector3.UP) | |
func _head_look(motion:Vector2): | |
_camera.rotation.x = clamp(_camera.rotation.x + motion.y * MOUSE_SENSITIVITY , -PI / 2 , PI / 2) | |
_camera.rotate_y(motion.x * MOUSE_SENSITIVITY) | |
_camera.orthonormalize() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment