gpt4 book ai didi

c++ - 沿opengl中的路径旋转

转载 作者:太空宇宙 更新时间:2023-11-04 12:36:32 25 4
gpt4 key购买 nike

我想沿着一条路径(正弦波)移动一个物体,让我们假设物体是一个过山车。它通过翻译移动,但我的问题是我还想根据路径旋转该对象。

i tried this code before translate but its not working.

if (x = -4.8)
{
glRotatef(89, 1, 1, 0);
}

my code with only translation looks like this. i want to add rotation here along sine waves

void object()
{ glPushMatrix();
glTranslatef(x, y, 0);

glColor3f(0.0f, 0.0f, 0.0f);//Set drawing color
glBegin(GL_QUADS);
glVertex2f(-0.3, 0.1);
glVertex2f(0.3, 0.1);
glVertex2f(0.3, -0.1);
glVertex2f(-0.3, -0.1);
glEnd();
glFlush();
glPopMatrix();
glFlush();
}

void drawsine()
{
glBegin(GL_LINE_STRIP);//Primitive
glColor3f(255, 0, 0);//Set drawing color
int i = 0;
float x = 0, y = 0;
for (x = -5; x < 6; x = x + 0.1)
{
y = (sin(3.142*x)) / 3.142*x;
glVertex2f(x, y);

//int j= 0;
sinex[i] = x;
siney[i] = y;
i++;
}
glEnd();
glFlush();
}

最佳答案

旋转角度取决于沿正弦波的方向 vector 。

可以通过减去2个位置来计算方向 vector 。当前位置之后的位置减去当前位置之前的位置,计算方向 vector 。在下面i是对象的当前位置:

dx = sinex[i+1] - sinex[i-1];
dy = siney[i+1] - siney[i-1];

旋转角度可以通过arcus tangent来计算使用 atan2 ,返回以弧度为单位的角度:

float ang_rad = atan2( dy, dx );

由于必须将角度传递给 glRotatef 以度为单位,必须先将角度从弧度转换为度,然后才能执行绕 z 轴的旋转。一个完整的圆圈有 360 度或 2* Pi弧度。所以从弧度到度数的比例 180/Pi:

float ang_deg = ang_rad * 180.0f / M_PI;
glRotatef( ang_deg, 0, 0, 1 );

以下 cde 片段显示了如何应用代码。请注意,没有边界检查。这意味着 i必须大于或等于 1 且小于点数 - 1 ( 1 <= i < 110 ):

#define _USE_MATH_DEFINES
#include <math.h>
{
// [...]

drawsine();

x = sinex[i];
y = siney[i];
dx = sinex[i+1] - sinex[i-1];
dy = siney[i+1] - siney[i-1];

object();

// [...]
}
void object()
{
glPushMatrix();
glTranslatef(x, y, 0);

float ang_rad = atan2( dy, dx );
float ang_deg = ang_rad * 180.0f / M_PI;
glRotatef( ang_deg, 0, 0, 1 );

glColor3f(0.0f, 0.0f, 0.0f);
glBegin(GL_QUADS);
glVertex2f(-0.3, 0.1);
glVertex2f(0.3, 0.1);
glVertex2f(0.3, -0.1);
glVertex2f(-0.3, -0.1);
glEnd();

glPopMatrix();
}

关于c++ - 沿opengl中的路径旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56202678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com