用弹丸击中点

时间:2014-10-25 01:13:36

标签: c# unity3d trigonometry

我正在尝试计算我的大炮需要达到目标点的正确角度。下面的代码始终将角度设置为90度。我正在使用c#和Unity。对我做错了什么建议?

        double x = -(source.x - position.x);
        double y = (source.y - position.y);
        double v = 500; //m/s
        double g = Physics2D.gravity.y;
        double sqrt = (v * v * v * v) - (g * (g * (x * x) + 2 * y * (v * v)));
        sqrt = Math.Sqrt(sqrt);
        double angleInRadians = Math.Atan2(((v * v) + sqrt), (g * x));

        double degrees = angleInRadians * Mathf.Rad2Deg; //This is always 90
        Vector3 angle = new Vector3(0,180,(float)degrees);

        _cannon.transform.localEulerAngles = angle;

2 个答案:

答案 0 :(得分:0)

根据Mathf.Atan2定义:

  

如果y为正且x为0,则θ=π/ 2.

x是第二个参数,因此您的g * x会产生0.基本数学告诉我们,如果任何或所有操作数都等于0,则可以这样做。

所以,实质上,要么:

  • -(source.x - position.x)
  • Physics2D.gravity.y

等于0.我认为引力的y值是罪魁祸首。

答案 1 :(得分:0)

对于寻找这个问题的解决方案的人来说,这是解决方案:

    private float _power = 0.5f;
    private float _mass = 0.5f;
    private float _powerMultiplier = 2000f; //Adjust this to lower or raise max reach

    public void Update()
    {
        Vector2 target = Global.Player1.CastlePosition;
        Vector2 source = transform.position;

        if (!CanHitCoordinate(source, target))
        {
            _power += 0.01f;
            return;
        }

        float angle = CalculateAngleToHitCoordinate(source, target);
        Vector3 newAngle = new Vector3(0, 0, angle);
        _cannon.transform.localEulerAngles = newAngle;
    }

    private float CalculateAngleToHitCoordinate(Vector2 source, Vector2 target) 
    {
        float power = _power * _powerMultiplier;
        float x = -(source.x - target.x);
        float y = -(source.y - target.y);


        float v = (power / mass) * Time.fixedDeltaTime;
        float g = -Physics2D.gravity.y; //Needs to be positive

        float sqrt = (v * v * v * v) - (g * (g * (x * x) + 2 * y * (v * v)));
        sqrt = Mathf.Sqrt(sqrt);

        double angleInRadians = Math.Atan((v * v + sqrt) / (g * x));
        return (float)angleInRadians * Mathf.Rad2Deg;
    }

    private float CalculateDelta(Vector2 source, Vector2 target)
    {
        float power = _power * _powerMultiplier;
        float x = (source.x - target.x);
        float y = -(source.y - target.y);


        float v = (power / 0.5f) * Time.fixedDeltaTime;
        float g = -Physics2D.gravity.y;
        return (v * v * v * v) - (g * (g * (x * x) + 2 * y * (v * v)));
    }

    public bool CanHitCoordinate(Vector2 source, Vector2 target)
    {
        return CalculateDelta(source, target) >= 0;
    }

这是针对其右侧目标的射击源。要向左侧的目标射击,只需对上述代码进行以下两处更改:

float x = (source.x - target.x); //Remove "-"
Vector3 newAngle = new Vector3(0, 180, angle); //Point towards the left