Griff1th

CircleMovement

Mar 7th, 2023 (edited)
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.73 KB | Gaming | 0 0
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3.  
  4. public class Movement : MonoBehaviour
  5. {
  6.     [SerializeField] private float _speed;
  7.     [SerializeField] private Transform _target;
  8.     [SerializeField] private Transform _prefab;
  9.      
  10.     private Vector2 TargetDirection => (_target.position - transform.position).normalized;  
  11.  
  12.     private void Update()
  13.     {
  14.         Vector2 roundDirection = GetDirectionAlongCircle();
  15.  
  16.         float weight = GetWeight();
  17.         Vector3 finalDirection = (1 - weight) * roundDirection + weight * TargetDirection;
  18.    
  19.         transform.position += finalDirection.normalized * Time.deltaTime * _speed;
  20.  
  21.         //Instantiate(_prefab, transform.position, Quaternion.identity);
  22.     }
  23.  
  24.     private float GetWeight()
  25.     {
  26.         float t = Mathf.InverseLerp(2, 4, Vector3.Distance(transform.position, _target.position));
  27.         float weight = Mathf.Lerp(0, 1, t);
  28.         return weight;
  29.     }
  30.  
  31.     private Vector2 GetDirectionAlongCircle()
  32.     {  
  33.         Vector2 r = transform.position - _target.position;
  34.         float angle = GetRotationAngle(r.magnitude, Time.deltaTime * _speed);
  35.         Vector2 rotatedR = RotateVector(r, angle);
  36.         Vector2 roundDirection = (rotatedR - r).normalized;
  37.         return roundDirection;
  38.     }
  39.  
  40.     private Vector2 RotateVector(Vector2 vector, float rad)
  41.     {
  42.         Vector2 right = new Vector2(Mathf.Cos(rad), Mathf.Sin(rad));
  43.         Vector2 up = new Vector2(-Mathf.Sin(rad), Mathf.Cos(rad));
  44.         return new Vector2(right.x * vector.x + up.x * vector.y,
  45.                            right.y * vector.x + up.y * vector.y);
  46.     }
  47.  
  48.     private float GetRotationAngle(float r, float chord) =>
  49.         Mathf.Asin(chord / (2 * r)) * 2;
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment