繁体   English   中英

C ++-Vector2D数学没有给我正确的结果

[英]c++ - Vector2D math not giving me the right results

我正在尝试为我的游戏创建一个vector2D类,但我认为数学有误。

当我创建一个新的vector2d对象时,它将在构造函数中自动将其x和y设置为1。

    Vector2D vec;

    std::cout << " x: " << vec.GetX() << " y: " << vec.GetY() << " angle rad: " << vec.GetAngleRad() << " magnitude: " << vec.GetMagnitude() << std::endl;



    system("pause");
    return 0;

它输出:
x:1
y:1
弧度角:0.785398
大小:1.41421
(这正是我所期望的)

但是问题是当我将任何内容解析为setAngle函数时,都会得到一些有线结果。

例如:

Vector2D vec;

vec.SetAngleRad(3);

std::cout << " x: " << vec.GetX() << " y: " << vec.GetY() << " angle rad: " << vec.GetAngleRad() << " magnitude: " << vec.GetMagnitude() << std::endl;



system("pause");
return 0;

我希望它以rad为单位输出角度:3
但是相反,我得到了弧度角:0.141593。

这是vector2D类(我试图注释我的代码,以便您可以看到我在编写代码时的想法):

#include "Vector2D.h"



Vector2D::Vector2D():
    _x(1.0f),
    _y(1.0f)
{

}


Vector2D::~Vector2D()
{

}

void Vector2D::SetX(float x)
{
    _x = x;
}

float Vector2D::GetX()
{
    return _x;
}


void Vector2D::SetY(float y)
{
    _y = y;
}

float Vector2D::GetY()
{
    return _y;
}


void Vector2D::SetAngleRad(float angle)
{
    float hypotenuse = GetMagnitude();

    SetX( cos(angle) * hypotenuse); // cos of angle = x / hypotenuse
                                    // so x = cos of angle * hypotenuse

    SetY( sin(angle) * hypotenuse); //sin of angle = y / hypotenuse
                                    // so y = sin of angle * hypotenuse
}

float Vector2D::GetAngleRad()
{
    float hypotenuse = GetMagnitude();
    return asin( _y / hypotenuse ); // if sin of angle A = y / hypotenuse
                                    // then asin of y / hypotenuse = angle
}


void Vector2D::SetMagnitude(float magnitude)
{
    float angle = GetAngleRad();
    float hypotenuse = GetMagnitude();

    SetX( (cos(angle) * hypotenuse) * magnitude ); // cos of angle = x / hypotenuse
                                                   // so cos of angle * hypotenuse = x
                                                   // multiplied by the new magnitude


    SetY( (sin(angle) * hypotenuse) * magnitude); //sin of angle = y / hypotenuse
                                                  // so sin of angle * hypotenuse = y
                                                  // multipied by the new magnitude
}

float Vector2D::GetMagnitude()
{
    return sqrt( (_x * _x) + (_y * _y) ); // a^2 + b^2 = c^2
                                          //so c = sqrt( a^2 + b^2 )
}

因此,如果有人可以向我解释我在做什么错,我将非常感激:)

要获得完整圆角的角度,必须同时使用带有atan2函数的y和x分量

return atan2( _y, _x );

注意结果范围-Pi..Pi ,如果需要范围0..2*Pi+2*Pi校正负一。

另一个问题:: :SetMagnitude方法实际上将当前幅度乘以magnitude乘数,而名称假定该方法应对其进行设置(因此,应用SetMagnitude(2)后的矢量长度2将具有幅度4)。

因此最好删除*hypotenuse乘法(或更改方法名称)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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