rj-action-library/Runtime/VirtualCameras/FollowCamera3D.cs

61 lines
1.3 KiB
C#
Raw Normal View History

2024-05-19 15:59:41 +00:00
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System;
using Godot;
namespace Rokojori
{
[Tool]
[GlobalClass]
public partial class FollowCamera3D:VirtualCamera3D
{
[Export]
public Node3D target;
[Export]
public float speed = 5;
[Export]
public float distance = 5;
[Export]
public float rotationSmoothingCoefficient = 0.1f;
Smoother smoother = new Smoother();
public override void _Process( double delta )
{
if ( target == null )
{
return;
}
var d = (float) delta;
Move( d );
Rotate( d );
}
void Move( float delta )
{
var direction = target.GlobalPosition - GlobalPosition;
if ( direction.Length() > distance )
{
var step = direction.Normalized() * speed * delta;
GlobalPosition += step;
}
}
void Rotate( float delta )
{
2024-09-14 06:41:52 +00:00
var currentRotation = Math3D.GetGlobalQuaternion( this );
2024-05-19 15:59:41 +00:00
LookAt( target.GlobalPosition, Vector3.Up, true );
2024-09-14 06:41:52 +00:00
var nextRotation = Math3D.GetGlobalQuaternion( this );
2024-05-19 15:59:41 +00:00
var smoothedRotation = smoother.SmoothWithCoefficient( currentRotation, nextRotation, rotationSmoothingCoefficient, delta );
2024-09-14 06:41:52 +00:00
Math3D.SetGlobalRotationTo( this, smoothedRotation );
2024-05-19 15:59:41 +00:00
}
}
}