-1

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

当我创建一个新的 vector2d 对象时,它会在构造函数中自动将其 x 和 y 设置为 1, 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 为单位输出角度,
但我得到的角度为 rad: 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 )
}

因此,如果有人可以向我解释我在这里做错了什么,我将不胜感激:)

4

1 回答 1

3

要获得全圆范围内的角度,您必须同时使用具有atan2功能的 y 和 x 分量

return atan2( _y, _x );

如果需要范围,请记下结果范围-Pi..Pi并纠正负数+2*Pi0..2*Pi

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

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

于 2017-02-17T07:31:38.527 回答