GodotComponentTest/components/GroundMotionComponent.cs

49 lines
1.6 KiB
C#
Raw Normal View History

using System;
2022-12-31 18:36:52 +01:00
using System.Numerics;
using Godot;
using Vector2 = Godot.Vector2;
using Vector3 = Godot.Vector3;
/// <summary>
/// </summary>
public class GroundMotionComponent
{
2022-12-31 18:36:52 +01:00
public float Accel = 50;
public float Damping = 0.2f;
public float MaxSpeed = 2;
public void PhysicsProcess(float delta, Entity entity, Vector3 target_position)
{
2022-12-31 18:36:52 +01:00
Vector2 plane_target_vector = new Vector2(target_position.x - entity.GlobalTranslation.x,
target_position.z - entity.GlobalTranslation.z);
2022-12-31 18:36:52 +01:00
float distance_error = plane_target_vector.Length();
2022-12-31 18:36:52 +01:00
if (distance_error < 0.01)
{
2022-12-31 18:36:52 +01:00
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);
}
2022-12-31 18:36:52 +01:00
entity.Velocity.x -= entity.Velocity.x * Damping;
entity.Velocity.z -= entity.Velocity.z * Damping;
entity.Velocity = entity.MoveAndSlide(entity.Velocity);
}
}