如何计算弹丸范围C#Unity 3D(2D项目)

时间:2018-07-09 09:46:42

标签: c# unity3d projectile

我在Wikipedia上找到了一个公式,其中描述了如何基于物理学来计算弹丸的射程,但是我仍然找不到使它起作用的方法。我要使用的公式是d =(v ^ 2 *sin2φ)/ g。如果有人可以用其他方式进行计算,那就可以了。请给出一个解决方案。下面的代码不能计算正确的位置,也不能在玩家(在这种情况下为弹丸)接触地面的下一个位置实例化蹦床。假设玩家将降落在(10,0),代码将蹦床实例化为(100,0)。

P.S。我的项目是2D,并且正在使用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");

}

}

1 个答案:

答案 0 :(得分:0)

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

相关问题