Advertisement
Guest User

Untitled

a guest
Feb 18th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. using System.Collections;
  2. using UnityEngine;
  3.  
  4. public class BallLauncher : MonoBehaviour
  5. {
  6.  
  7. public Rigidbody ball;
  8. public Transform target;
  9.  
  10. public float h = 25;
  11. public float gravity = -18;
  12.  
  13. public bool debugPath;
  14.  
  15. public LineRenderer line;
  16.  
  17. void Start ()
  18. {
  19. ball.useGravity = false;
  20. }
  21.  
  22. void Update ()
  23. {
  24. if (Input.GetKeyDown (KeyCode.Space))
  25. {
  26. Launch ();
  27. }
  28.  
  29. if (debugPath)
  30. {
  31. DrawPath ();
  32. }
  33. }
  34.  
  35. void Launch ()
  36. {
  37. Physics.gravity = Vector3.up * gravity;
  38. ball.useGravity = true;
  39. ball.velocity = CalculateLaunchData ().initialVelocity;
  40. }
  41.  
  42. LaunchData CalculateLaunchData ()
  43. {
  44. float displacementY = target.position.y - ball.position.y;
  45. Vector3 displacementXZ = new Vector3 (target.position.x - ball.position.x, 0, target.position.z - ball.position.z);
  46. float time = Mathf.Sqrt (-2 * h / gravity) + Mathf.Sqrt (2 * (displacementY - h) / gravity);
  47. Vector3 velocityY = Vector3.up * Mathf.Sqrt (-2 * gravity * h);
  48. Vector3 velocityXZ = displacementXZ / time;
  49.  
  50. return new LaunchData (velocityXZ + velocityY * -Mathf.Sign (gravity), time);
  51. }
  52.  
  53. void DrawPath ()
  54. {
  55. LaunchData launchData = CalculateLaunchData ();
  56. Vector3 previousDrawPoint = ball.position;
  57.  
  58. int resolution = 30;
  59. for (int i = 1; i <= resolution; i++)
  60. {
  61. float simulationTime = i / (float) resolution * launchData.timeToTarget;
  62. Vector3 displacement = launchData.initialVelocity * simulationTime + Vector3.up * gravity * simulationTime * simulationTime / 2f;
  63. Vector3 drawPoint = ball.position + displacement;
  64.  
  65. Debug.DrawLine (previousDrawPoint, drawPoint, Color.green);
  66. previousDrawPoint = drawPoint;
  67. }
  68. }
  69.  
  70. struct LaunchData
  71. {
  72. public readonly Vector3 initialVelocity;
  73. public readonly float timeToTarget;
  74.  
  75. public LaunchData (Vector3 initialVelocity, float timeToTarget)
  76. {
  77. this.initialVelocity = initialVelocity;
  78. this.timeToTarget = timeToTarget;
  79. }
  80.  
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement