apieceoffruit

Unity Software: Steering Behaviours

Dec 10th, 2021 (edited)
824
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.32 KB | None | 0 0
  1.     public class SteeringMovement
  2.     {
  3.         Vector3 _velocity;
  4.         Vector3 _acceleration;
  5.         Vector3 _position;
  6.         public Vector3 Target;
  7.  
  8.         public float ArriveRadius = 3;
  9.         public SteeringMovement(float maxSpeed = 15,float maxForce = 5)
  10.         {
  11.             MaxSpeed = maxSpeed;
  12.             MaxForce = maxForce;
  13.         }
  14.  
  15.         public float MaxForce { get; set; }
  16.         public float MaxSpeed { get; set; }
  17.  
  18.         public void UpdateMovement(Transform owner)
  19.         {
  20.             _position = owner.position;
  21.             ApplyForce(Arrive(Target,ArriveRadius));
  22.             UpdateVehicle(Time.deltaTime);
  23.             ApplyToTransform(owner);
  24.             ClearForces();
  25.         }
  26.        
  27.         void ApplyForce(Vector3 force) => _acceleration += force;
  28.  
  29.         void ClearForces() => _acceleration = Vector3.zero;
  30.        
  31.         void UpdateVehicle(float time)
  32.         {
  33.             _position += _velocity * time;
  34.             _velocity += _acceleration;
  35.             ClearForces();
  36.         }
  37.        
  38.         public void ApplyToTransform(Transform owner)
  39.         {
  40.             owner.position = _position;
  41.             if (_velocity.magnitude < 0.1f) return;
  42.            
  43.             var desiredRotation = Quaternion.LookRotation(_velocity);
  44.             owner.rotation = Quaternion.Lerp(owner.rotation,desiredRotation,Time.deltaTime*12);
  45.         }
  46.        
  47.  
  48.         Vector3 Seek(Vector3 target)
  49.         {
  50.             var desired = target - _position;
  51.             desired.Normalize();
  52.             desired *= MaxSpeed;
  53.             var steeringForce = desired - _velocity;
  54.             return Vector3.ClampMagnitude(steeringForce,MaxForce);
  55.         }
  56.        
  57.         Vector3 Arrive(Vector3 target,float radius)
  58.         {
  59.             var desired = target - _position;
  60.             var distance = desired.magnitude;
  61.             desired.Normalize();
  62.  
  63.             var speed = MaxSpeed;
  64.             if (distance < radius)
  65.                 speed = map(distance, 0, radius, 0, MaxSpeed);
  66.  
  67.             desired *= speed;
  68.             var steeringForce = desired - _velocity;
  69.             return Vector3.ClampMagnitude(steeringForce,MaxForce);
  70.         }
  71.        
  72.         float map(float val, float a1, float a2, float b1, float b2) =>
  73.             b1 + (val-a1)*(b2-b1)/(a2-a1);
  74.     }
Add Comment
Please, Sign In to add comment