Skip to content

Instantly share code, notes, and snippets.

@shryder
Created January 22, 2020 19:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shryder/5db7e72775c4749ffea38ccf159552a2 to your computer and use it in GitHub Desktop.
Save shryder/5db7e72775c4749ffea38ccf159552a2 to your computer and use it in GitHub Desktop.
Limit rotation on the Y axis Godot
+ Player
- Body
- MeshInstance
- Head
- Camera
extends KinematicBody
export var speed = 10
export var acceleration = 5
export var gravity = 0.98
export var jump_power = 30
export var mouse_sensitivity = 0.3
onready var head = $Head
onready var camera = $Head/Camera
onready var body = $Body;
var velocity = Vector3()
func _ready():
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _input(event):
if(paused):
return;
if event is InputEventMouseMotion:
# Rotate the whole player instead of just the head.
head.rotate_y(deg2rad(-event.relative.x * mouse_sensitivity));
camera.rotate_x(deg2rad(-event.relative.y * mouse_sensitivity));
# We can make use of the rotation_degrees property and the method clamp
var cam_rotation = camera.rotation_degrees;
cam_rotation.x = clamp(cam_rotation.x, -90, 90);
camera.rotation_degrees = cam_rotation;
# Limit looking far right/left too
var head_rotation = head.rotation_degrees;
head_rotation.y = clamp(head_rotation.y, -90, 90);
head.rotation_degrees = head_rotation;
func _process(delta):
if Input.is_action_just_pressed("ui_cancel"):
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE);
func _physics_process(delta):
var head_basis = head.get_global_transform().basis;
var direction = Vector3();
if Input.is_action_pressed("move_forward"):
direction -= head_basis.z;
# When player moves forward. Rotate body to be in the same direction as the head/camera
if(head.rotation.y != 0):
var y_direction = head.global_transform.basis.get_euler().y;
# Reset body and head rotation and rotate the whole Player now.
body.rotation.y = 0;
head.rotation.y = 0;
self.rotation.y = y_direction;
elif Input.is_action_pressed("move_backward"):
direction += head_basis.z
if Input.is_action_pressed("move_left"):
direction -= head_basis.x
elif Input.is_action_pressed("move_right"):
direction += head_basis.x
direction = direction.normalized()
velocity = velocity.linear_interpolate(direction * speed, acceleration * delta)
velocity.y -= gravity
if Input.is_action_just_pressed("move_jump") and is_on_floor():
velocity.y += jump_power
velocity = move_and_slide(velocity, Vector3.UP)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment