AceField/Scripts/Player.cs
2024-08-05 23:54:22 +08:00

104 lines
2.4 KiB
C#

using CodingLand.Scripts.Logic;
using Godot;
namespace CodingLand.Scripts;
public partial class Player : CharacterBody2D
{
private int _currentPlayerId = 1;
[Export] public float MaxSpeed = 400f;
[Export] public float Acceleration = 500f;
[Export] public float Deceleration = 500f;
[Export] public float RotationSpeed = 5f;
[Export] public int Reach = 5;
[Export] public Camera2D PlayerCamera;
[Export] public PlayerInput PlayerInput;
[Export] public float PlayerDashAcceleration = 2f;
[Export]
public int PlayerId
{
get => _currentPlayerId;
set
{
_currentPlayerId = value;
PlayerInput.SetMultiplayerAuthority(value);
}
}
public void SetPlayerId(int id)
{
PlayerId = id;
PlayerInput.SetMultiplayerAuthority(id);
}
private TilesManager _tilesMgr;
public override void _Ready()
{
if (PlayerId == Multiplayer.GetUniqueId())
PlayerCamera.Enabled = true;
_tilesMgr = GetNode<TilesManager>("../Tiles");
}
public override void _Process(double delta)
{
var vec = GetGlobalMousePosition();
if (PlayerInput.BuildingAt == Vector2.Zero) return;
var distance = Position.DistanceTo(vec);
if (distance <= Reach * _tilesMgr.TileSize)
{
// Able to build
Rpc(nameof(AddTile), vec);
}
PlayerInput.BuildingAt = Vector2.Zero;
}
public override void _PhysicsProcess(double delta)
{
var input = PlayerInput.MovementDirection;
if (input != Vector2.Zero)
{
input = input.Normalized();
Velocity = Velocity.MoveToward(input * MaxSpeed, Acceleration * (float)delta);
var finalRotation = input.Angle() + Mathf.Pi / 2;
Rotation = Mathf.LerpAngle(Rotation, finalRotation, RotationSpeed * (float)delta);
}
else
{
Velocity = Velocity.MoveToward(Vector2.Zero, Deceleration * (float)delta);
}
var dashCountdown = GetNode<Timer>("DashCountdown");
if (PlayerInput.IsDashing && dashCountdown.IsStopped())
{
PlayerInput.IsDashing = false;
Velocity *= PlayerDashAcceleration;
dashCountdown.Start();
}
Position += Velocity * (float)delta;
MoveAndSlide();
}
[Rpc(mode: MultiplayerApi.RpcMode.AnyPeer, CallLocal = true)]
public void AddTile(Vector2 pos)
{
if (_tilesMgr.GetTileByPosition<Node2D>(pos) != null) return;
var tileVec = new Vector2(_tilesMgr.TileSize, _tilesMgr.TileSize);
var blueprint = GD.Load<PackedScene>("res://Scenes/Tiles/Brick.tscn");
var instance = blueprint.Instantiate<Node2D>();
instance.Position = pos.Snapped(tileVec);
_tilesMgr.AddChild(instance);
}
}