简体   繁体   中英

How to calculate projectile range C# Unity 3D (2D project)

I found a formula on Wikipedia where it is described how to calculate Range of a Projectile based on physics, but I still can't find a way to make it work. Formula that i want to use is d=(v^2*sin2φ)/g . If anyone can calculate in another way it's okay. Just give a solution. Following code is not calculating correct position, and is not instantiating trampoline at next position where player (projectile in this case) will touch ground. Let's suppose player will land at (10,0), code is instantiating trampoline at (100,0).

PS My project is 2D and it's being developed with C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NextDropLocation : MonoBehaviour {

public GameObject trampoline, player;
float speed;

float CalculateAngle()
{
    var dir = player.transform.position;
    var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    return angle;
}

private void FixedUpdate()
{
    speed = player.GetComponent<Rigidbody2D>().velocity.magnitude;
}

float InstantiateNext(float speed, float angle)
{
    return (Mathf.Pow(speed, 2) * 2 * Mathf.Sin(angle) * Mathf.Cos(angle) / 9.81f); //formula from Wikipedia
}

private void OnCollisionEnter2D(Collision2D collision)
{
    var angle = CalculateAngle();
    if (collision.gameObject.tag == "Trampoline")
    {
        player.GetComponent<Rigidbody2D>().AddForce(new Vector2(5, 5), ForceMode2D.Impulse);
        Instantiate(trampoline, new Vector3(InstantiateNext(speed, angle), -3.65f), player.transform.rotation);

    }
    else
        print("You landed on the ground. Game Over!");
}

// Use this for initialization
void Start () {
    player = GameObject.FindGameObjectWithTag("Player");

}

}

它可能没有给出正确的范围,因为您可以使用此公式计算地球重力的范围,但是您使用的是自定义重力,并且对象具有自定义的权重,因此您只需要对公式进行一些调整即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM