Advertisement
Guest User

Untitled

a guest
Jun 19th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. public Image aim;
  2. public Rigidbody2D player;
  3. public Transform firePoint;
  4.  
  5. private void UpdateAim()
  6. {
  7. Vector2 target = Input.mousePosition;
  8.  
  9. aim.transform.position = target;
  10.  
  11. Vector2 center = player.position;
  12. Vector2 firepoint = firePoint.position;
  13. Vector2 fromFirepoint = center - firepoint;
  14. float radius = fromFirepoint.magnitude;
  15.  
  16. Debug.DrawRay(center, -fromFirepoint);
  17.  
  18. Debug.DrawRay(target, fromFirepoint, Color.yellow);
  19.  
  20. Vector2 newTarget = FindCircleIntersection(center, radius, target, fromFirepoint);
  21.  
  22. Debug.DrawLine(target, newTarget, Color.green);
  23.  
  24. Debug.DrawLine(firepoint, target, Color.red);
  25. Debug.DrawRay(firepoint, player.transform.right*(target-firepoint).magnitude, Color.white);
  26.  
  27. Vector2 toTarget = newTarget - center;
  28.  
  29. float angle = Vector2.SignedAngle(Vector2.right, toTarget);
  30.  
  31. float lerp = (newTarget - target).sqrMagnitude / fromFirepoint.sqrMagnitude;
  32.  
  33. float alpha = Mathf.Lerp(Vector2.SignedAngle(player.transform.right, -fromFirepoint), 0F, lerp);
  34.  
  35. player.transform.rotation = Quaternion.AngleAxis(angle - alpha, Vector3.forward);
  36. }
  37.  
  38. private Vector2 FindCircleIntersection(Vector2 center, float radius, Vector2 origin, Vector2 direction)
  39. {
  40. Vector2 union = origin - center;
  41.  
  42. float a = Vector2.Dot(direction, direction);
  43. float b = 2F * Vector2.Dot(union, direction);
  44. float c = Vector2.Dot(union, union) - radius * radius;
  45. float d = b * b - 4F * a * c;
  46.  
  47. if (d >= 0F)
  48. {
  49. d = Mathf.Sqrt(d);
  50.  
  51. float t1 = (-b - d) / (2F * a);
  52.  
  53. if (t1 >= 0F && t1 <= 1F)
  54. return new Vector2(origin.x + t1 * direction.x, origin.y + t1 * direction.y);
  55.  
  56. float t2 = (-b + d) / (2F * a);
  57.  
  58. if (t1 < 0F && t2 >= 0F)
  59. return origin;
  60. }
  61.  
  62. return origin + direction;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement