Search Unity

Calculate Projectile Range (C#, 2D project)

Discussion in 'Physics' started by K97, Jul 9, 2018.

  1. K97

    K97

    Joined:
    Mar 24, 2016
    Posts:
    10
    Hi, i found two formulas on internet which describes the way to calculate Range of a Projectile. First one is instantiating a trampoline in wrong location, and the second one is not instantiating nothing at all. I am just asking if anyone can help me with that. I will write below code that i wrote so far, so you can help me to debug it, or maybe you can give me another formula which will work.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class NextDropLocation : MonoBehaviour {
    6.  
    7.     public GameObject trampoline, player;
    8.     float speed;
    9.  
    10.     float CalculateAngle()
    11.     {
    12.         var dir = player.transform.position;
    13.         var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    14.         return angle;
    15.     }
    16.  
    17.     private void FixedUpdate()
    18.     {
    19.         speed = player.GetComponent<Rigidbody2D>().velocity.magnitude;
    20.     }
    21.  
    22.     float InstantiateNext(float speed, float angle)
    23.     {
    24.         return 2 * Mathf.Cos(angle) * speed * Mathf.Sqrt(2 * Mathf.Sin(angle) * speed / 9.81f); //This produces following error: transform.position assign attempt for 'mushroom2(Clone)' is not valid. Input position is { NaN, -3.650000, 0.000000 }.
    25.         //return (Mathf.Pow(speed, 2) * 2 * Mathf.Sin(angle) * Mathf.Cos(angle) / 9.81f); //This instantiates trampoline in wrong location
    26.     }
    27.  
    28.     private void OnCollisionEnter2D(Collision2D collision)
    29.     {
    30.         var angle = CalculateAngle();
    31.         if (collision.gameObject.tag == "Mushroom")
    32.         {
    33.             player.GetComponent<Rigidbody2D>().AddForce(new Vector2(5, 5), ForceMode2D.Impulse);
    34.             Instantiate(trampoline, new Vector3(InstantiateNext(speed, angle), -3.65f), player.transform.rotation);
    35.  
    36.         }
    37.         else
    38.             print("You landed on the ground. Game Over!");
    39.     }
    40.  
    41.     // Use this for initialization
    42.     void Start () {
    43.         player = GameObject.FindGameObjectWithTag("Player");
    44.        
    45.     }
    46.    
    47.    
    48. }
    49.