spes/Spaceflight/Scripts/FlightController.cs

72 lines
2.9 KiB
C#

using Godot;
using System;
public partial class FlightController : Node3D {
Camera3D PlayerCam;
Vector3 AngularVelocity;
Vector3 LinearVelocity;
public override void _Ready() {
this.PlayerCam = this.GetNode<Camera3D>("MainCamera");
this.PlayerCam.Current = true;
}
public override void _Process(double deltaSeconds) {
float FlightPitch = Input.GetAxis("FlightPitch-", "FlightPitch+");
float FlightYaw = Input.GetAxis("FlightYaw-", "FlightYaw+");
float FlightRoll = Input.GetAxis("FlightRoll-", "FlightRoll+");
Vector3 FlightSpin = new Vector3(-FlightPitch, FlightYaw, FlightRoll) * (float)deltaSeconds;
if (FlightSpin != Vector3.Zero) {
Quaternion quat = new Quaternion(this.GlobalTransform.Basis);
Vector3 LocalAccel = FlightSpin * 100f * (float)deltaSeconds;
if (quat.GetAxis().LengthSquared() != 0f) {
this.AngularVelocity -= LocalAccel.Rotated(quat.GetAxis().Normalized(), quat.GetAngle());
}
else {
this.AngularVelocity -= LocalAccel;
}
}
this.AngularVelocity *= (float)(1.0 - deltaSeconds * 2.0);
if (this.AngularVelocity.Length() > 0f) {
Quaternion rotationThisFrame = Quaternion.FromEuler(this.AngularVelocity * (float)deltaSeconds);
if (rotationThisFrame.GetAxis().Normalized().LengthSquared() != 0f) {
this.GlobalRotate(rotationThisFrame.GetAxis().Normalized(), rotationThisFrame.GetAngle());
}
}
float FlightStrafe = Input.GetAxis("FlightStrafe-", "FlightStrafe+");
float FlightElevate = Input.GetAxis("FlightElevate-", "FlightElevate+");
float FlightThrust = Input.GetAxis("FlightThrust-", "FlightThrust+");
Vector3 FlightMovement = new Vector3(FlightStrafe, FlightElevate, -FlightThrust) * (float)deltaSeconds;
if (FlightMovement != Vector3.Zero) {
Quaternion quat = new Quaternion(this.GlobalTransform.Basis);
Vector3 LocalAccel = FlightMovement * 100f * (float)deltaSeconds;
if (quat.GetAxis().LengthSquared() != 0f) {
this.LinearVelocity += LocalAccel.Rotated(quat.GetAxis().Normalized(), quat.GetAngle());
}
else {
this.LinearVelocity += LocalAccel;
}
}
if (this.LinearVelocity.Length() > 0f) {
Vector3 movementThisFrame = this.LinearVelocity * (float)deltaSeconds;
this.GlobalTranslate(movementThisFrame);
}
}
public override void _Input(InputEvent @event) {
base._Input(@event);
if (@event is InputEventKey keyEvent) {
if (keyEvent.Keycode == Key.Escape) {
GetTree().Root.PropagateNotification((int)NotificationWMCloseRequest);
GetTree().Quit();
}
}
}
}