Griff1th

CosProjectionDot

Mar 25th, 2023
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | Gaming | 0 0
  1. using UnityEngine;
  2.  
  3. public class NewBehaviourScript : MonoBehaviour
  4. {
  5.     [SerializeField] private Vector2 _a;
  6.     [SerializeField] private Vector2 _b;
  7.     [SerializeField] private float _aAngle = 45;
  8.     [SerializeField] private float _bAngle;
  9.     [SerializeField] private float _aMagnitude = 1;
  10.     [SerializeField] private float _bMagnitude = 1;
  11.  
  12.     private void Update()
  13.     {
  14.         _a = Vector2Extension.GetRotatedVector(Vector2.right, _aAngle * Mathf.Deg2Rad) * _aMagnitude;
  15.         _b = Vector2Extension.GetRotatedVector(Vector2.right, _bAngle * Mathf.Deg2Rad) * _bMagnitude;        
  16.        
  17.         float dot = Vector2.Dot(_a, _b);
  18.         float cos = dot / (_b.magnitude * _a.magnitude);
  19.         float AonBProjection = dot / (_b.magnitude);
  20.  
  21.         Debug.DrawRay(transform.position, _a, Color.cyan);
  22.         Debug.DrawRay(transform.position, _b, Color.magenta);
  23.         Debug.DrawRay(transform.position + Vector3.down * 0.01f, _b.normalized * cos, Color.red);
  24.         Debug.DrawRay(transform.position + Vector3.down * 0.02f, _b.normalized * AonBProjection, Color.green);
  25.         Debug.DrawRay(transform.position + Vector3.down * 0.03f, _b.normalized * dot, Color.blue);
  26.         Debug.DrawLine(Vector3.down * 0.02f + (Vector3)_b.normalized * AonBProjection, (Vector3)_a, Color.yellow);
  27.     }
  28. }
  29.  
  30. public static class Vector2Extension
  31. {
  32.     public static Vector2 GetDirectionAlongCircle(Vector2 targetPositioin, Vector2 selfPoisition, float speed)
  33.     {
  34.         Vector2 r = selfPoisition - targetPositioin;
  35.         float angle = GetRotationAngle(r.magnitude, speed);
  36.         Vector2 rotatedR = GetRotatedVector(r, angle);
  37.         return (rotatedR - r).normalized;      
  38.  
  39.         float GetRotationAngle(float r, float chord) =>
  40.             Mathf.Asin(chord / (2 * r)) * 2;
  41.     }
  42.     public static Vector2 GetRotatedVector(Vector2 vector, float rad)
  43.     {
  44.         Vector2 right = new Vector2(Mathf.Cos(rad), Mathf.Sin(rad));
  45.         Vector2 up = new Vector2(-Mathf.Sin(rad), Mathf.Cos(rad));
  46.         return new Vector2(right.x * vector.x + up.x * vector.y,
  47.                            right.y * vector.x + up.y * vector.y);
  48.     }
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment