moraepado/mainScene/Player.gd
2023-10-07 18:29:52 +09:00

82 lines
2 KiB
GDScript

extends KinematicBody
var camera_angle = 0
var mouse_sensitivity = 0.3
var camera_change = Vector2()
var velocity = Vector3()
var direction = Vector3()
var _oldtf = Transform()
#fly variables
const FLY_SPEED = 20
const FLY_ACCEL = 4
var mouse_captured = true
func _ready():
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _physics_process(delta):
if mouse_captured:
aim()
fly(delta)
# emit signal - playerinfo_updated
var tf = $Head/Camera.get_global_transform_interpolated()
if tf != _oldtf:
Events.emit_signal("player_transform_updated", $Head/Camera.get_global_translation(), $Head.global_rotation.y)
_oldtf = tf
if Input.is_action_just_pressed('toggle_mouse'):
if mouse_captured:
mouse_captured = false
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
else:
mouse_captured = true
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _input(event):
if event is InputEventMouseMotion:
camera_change = event.relative
func fly(delta):
# reset the direction of the player
direction = Vector3()
# get the rotation of the camera
var aim = $Head/Camera.get_global_transform().basis
# check input and change direction
if Input.is_action_pressed("move_forward"):
direction -= aim.z
if Input.is_action_pressed("move_backward"):
direction += aim.z
if Input.is_action_pressed("move_left"):
direction -= aim.x
if Input.is_action_pressed("move_right"):
direction += aim.x
direction = direction.normalized()
# where would the player go at max speed
var target = direction * FLY_SPEED
# calculate a portion of the distance to go
velocity = velocity.linear_interpolate(target, FLY_ACCEL * delta)
# move
move_and_slide(velocity)
func aim():
if camera_change.length() > 0:
$Head.rotate_y(deg2rad(-camera_change.x * mouse_sensitivity))
var change = -camera_change.y * mouse_sensitivity
if change + camera_angle < 90 and change + camera_angle > -90:
$Head/Camera.rotate_x(deg2rad(change))
camera_angle += change
camera_change = Vector2()