Advertisement
Guest User

Untitled

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