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

61 lines
1.3 KiB
C#

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 )
{
var currentRotation = Math3D.GetGlobalQuaternion( this );
LookAt( target.GlobalPosition, Vector3.Up, true );
var nextRotation = Math3D.GetGlobalQuaternion( this );
var smoothedRotation = smoother.SmoothWithCoefficient( currentRotation, nextRotation, rotationSmoothingCoefficient, delta );
Math3D.SetGlobalRotationTo( this, smoothedRotation );
}
}
}