GodotComponentTest/components/GroundMotionComponent.cs

49 lines
1.6 KiB
C#

using System;
using System.Numerics;
using Godot;
using Vector2 = Godot.Vector2;
using Vector3 = Godot.Vector3;
/// <summary>
/// </summary>
public class GroundMotionComponent
{
public float Accel = 50;
public float Damping = 0.2f;
public float MaxSpeed = 2;
public void PhysicsProcess(float delta, Entity entity, Vector3 target_position)
{
Vector2 plane_target_vector = new Vector2(target_position.x - entity.GlobalTranslation.x,
target_position.z - entity.GlobalTranslation.z);
float distance_error = plane_target_vector.Length();
if (distance_error < 0.01)
{
entity.Velocity = Vector3.Zero;
} else {
Vector2 plane_velocity = new Vector2(entity.Velocity.x, entity.Velocity.z);
plane_velocity = plane_velocity + plane_target_vector / distance_error * Accel * delta;
float projected_step = plane_target_vector.Dot(plane_velocity * delta);
GD.Print("Projected step: " + projected_step);
if (projected_step > 1)
{
plane_velocity /= projected_step;
}
float plane_speed = plane_velocity.Length();
if (plane_speed > MaxSpeed)
{
plane_velocity *= MaxSpeed / plane_speed;
}
entity.Velocity = new Vector3(
plane_velocity.x, 0, plane_velocity.y);
}
entity.Velocity.x -= entity.Velocity.x * Damping;
entity.Velocity.z -= entity.Velocity.z * Damping;
entity.Velocity = entity.MoveAndSlide(entity.Velocity);
}
}