2D旋转问题C Directx

2D Rotation Issue C++ DirectX

本文关键字:Directx 问题 旋转 2D      更新时间:2023-10-16

,因此我试图旋转窗口中的另一点,并用DirectX绘制它。我的问题是旋转形状很奇怪:

http://prntscr.com/iynh5f

我正在做的只是在窗口的中心旋转一个点,并在点之间绘制线。

vec2_t vecCenter1 { gui.iWindowSize[ 0 ] / 2.f, gui.iWindowSize[ 1 ] / 2.f };
for ( float i { 0.f }; i < 360.f; i += 2.f )
{
    vec2_t vecLocation { vecCenter1.x, vecCenter1.y - 100.f };
    static vec2_t vecOldLocation = vecLocation;
    vecLocation.Rotate( i, vecCenter1 );
    if ( i > 0.f )
        Line( vecOldLocation, vecLocation, 2, true, D3DCOLOR_ARGB( 255, 255, 255, 255 ) );
    vecOldLocation = vecLocation;
}

这是我的旋转:

void vec2_t::Rotate( float flDegrees, vec2_t vecSubtractVector ) 
{
    flDegrees = ToRadian( flDegrees );
    float flSin = sin( flDegrees );
    float flCos = cos( flDegrees );
    *this -= vecSubtractVector;
    x = x * flCos - y * flSin;
    y = x * flSin + y * flCos;
    *this += vecSubtractVector;
}

我尝试了几种不同的旋转方法,但它们似乎都没有用。如果有人能告诉我我做错了什么,我会很感激。

键行:

x = x * flCos - y * flSin;
y = x * flSin + y * flCos;  << problem 

第二行使用x修改值,而它应使用原始。您必须在更新之前缓存两个坐标(或至少x(:

void vec2_t::Rotate( float flDegrees, vec2_t vecSubtractVector ) 
{
    float flRadians = ToRadian( flDegrees );
    float flSin = sin( flRadians );
    float flCos = cos( flRadians );
    // cache both values + pre-subtract
    float xOld = x - vecSubtractVector.x;
    float yOld = y - vecSubtractVector.y;
    // perform the rotation and add back
    x = xOld * flCos - yOld * flSin + vecSubtractVector.x;
    y = xOld * flSin + yOld * flCos + vecSubtractVector.y;
}

  • 要摆脱循环中的if stitegent,只需计算循环以外的第一个点,然后从delta值开始而不是零
  • 不要使用static,因为它可能会导致线程安全问题(尽管在您的情况下并不重要( - 只需在循环之外声明
  • 您似乎缺少线段 - 条件需要是<= 360.f(理想情况下是Epsilon(

    vec2_t vecCenter1 = { gui.iWindowSize[ 0 ] / 2.f, gui.iWindowSize[ 1 ] / 2.f };
    const float delta_angle = 2.f;
    vec2_t vecOldLocation = { vecCenter1.x, vecCenter1.y - 100.f };
    for ( float i = delta_angle; i <= 360.f; i += delta_angle ) // complete cycle
    {
        vec2_t vecLocation = { vecCenter1.x, vecCenter1.y - 100.f };
        vecLocation.Rotate( i, vecCenter1 );
        Line( vecOldLocation, vecLocation, 2, true,   // no if statement
              D3DCOLOR_ARGB( 255, 255, 255, 255 ) );
        vecOldLocation = vecLocation;
    }