Godot-SpaceShooter/Scripts/PlayerShip.cs

93 lines
3.0 KiB
C#

using Godot;
namespace Scripts;
public partial class PlayerShip : Node3D {
[Export] private float moveVelocity = 10f;
[Export] private float rotVelocity = 15f;
[Export] private Node3D jet;
[Export] private RigidBody3D playerRb;
private const float jetTimerMax = 0.5f;
private float jetTimer = jetTimerMax;
private Vector3 moveDir;
private Vector3 rotDir;
private const string PLAYER_MOVE_FORWARD = "Player_Move_Forward";
private const string PLAYER_MOVE_BACKWARDS = "Player_Move_Backwards";
private const string PLAYER_MOVE_LEFT = "Player_Move_Left";
private const string PLAYER_MOVE_RIGHT = "Player_Move_Right";
private bool jetActive;
private bool JetActive {
get => jetActive;
set {
jetTimer = jetTimerMax;
jetActive = value;
jet.Visible = value;
// GD.Print($"JetActive is {value}");
}
}
public override void _Ready() => Position = new(0, 0, 5);
public override void _PhysicsProcess(double delta) {
HandleMovement(delta);
if (JetActive) {
jetTimer -= (float)delta;
// GD.Print($"{jetTimer}/{jetTimerMax}");
}
if (jetTimer < 0) JetActive = false;
}
public override void _UnhandledInput(InputEvent @event) {
moveDir = Vector3.Zero;
rotDir = Vector3.Zero;
if (Input.IsAnythingPressed()) JetActive = true;
// Vector2 inputVector = Input.GetVector(PLAYER_MOVE_FORWARD, PLAYER_MOVE_BACKWARDS, PLAYER_MOVE_LEFT, PLAYER_MOVE_RIGHT);
// moveDir = new Vector3(inputVector.X, 0, inputVector.Y) * moveVelocity;
if (Input.IsActionPressed(PLAYER_MOVE_FORWARD)) moveDir.Z -= moveVelocity;
if (Input.IsActionPressed(PLAYER_MOVE_BACKWARDS)) moveDir.Z += moveVelocity;
if (Input.IsActionPressed(PLAYER_MOVE_LEFT)) moveDir.X -= moveVelocity;
if (Input.IsActionPressed(PLAYER_MOVE_RIGHT)) moveDir.X += moveVelocity;
if (Input.IsActionJustPressed(PLAYER_MOVE_FORWARD)) rotDir.X = -rotVelocity;
if (Input.IsActionJustPressed(PLAYER_MOVE_BACKWARDS)) rotDir.X = +rotVelocity;
if (Input.IsActionJustPressed(PLAYER_MOVE_LEFT)) rotDir.Z = -rotVelocity * 2;
if (Input.IsActionJustPressed(PLAYER_MOVE_RIGHT)) rotDir.Z = +rotVelocity * 2;
if (Input.IsActionJustReleased(PLAYER_MOVE_LEFT) || Input.IsActionJustReleased(PLAYER_MOVE_RIGHT)) rotDir = Vector3.Zero;
}
private void HandleMovement(double delta) {
if (moveDir != Vector3.Zero) {
KinematicCollision3D collision = playerRb.MoveAndCollide(moveDir * (float)delta);
if (collision?.GetCollider() is Node3D collider) GD.Print($"{Name} collides with {collider.GetParentNode3D().Name}");
}
// Position += moveDir;
playerRb.RotationDegrees = rotDir;
// playerRb.Rotate(rotDir.Normalized(), rotVelocity * (float)delta);
// RotationDegrees = rotDir * (float)delta;
CheckBoundaries();
}
private void CheckBoundaries() {
Vector3 correctedPos = Position;
correctedPos.X = Position.X switch {
< -3.3f => -3.3f,
> 3.3f => 3.3f,
_ => correctedPos.X
};
correctedPos.Z = Position.Z switch {
< -5.2f => -5.2f,
> 5.2f => 5.2f,
_ => correctedPos.Z
};
Position = correctedPos;
}
}