使用贝塞尔曲线的运动路径

问题描述:

我必须使用贝塞尔曲线创建运动路径。在运行下面的程序时,我得到了应该是我的运动路径曲线的控制多边形的值,我可以通过“printf”语句来检查它们,但是我实际上并没有得到曲线。使用贝塞尔曲线的运动路径

我做了什么错了,我可怎么解决呢?

#include "stdafx.h" 
#include <gl/glut.h> 
#include <cstdio> 



struct point 
{ 
float x; 
float y; 
}; 

// simple linear interpolation between two points 
void lirp(point& dest, const point& a, const point& b, const float t) 
{ 
dest.x = a.x + (b.x - a.x)*t; 
dest.y = a.y + (b.y - a.y)*t; 
} 

// evaluate a point on a bezier-curve. t goes from 0 to 1.0 
void bezier(point &dest, const point& a, const point& b, const point& c, const point& d, const float t) 
{ 
point ab, bc, cd, abbc, bccd; 

lirp(ab, a, b, t);   // point between a and b 
lirp(bc, b, c, t);   // point between b and c 
lirp(cd, c, d, t);   // point between c and d 
lirp(abbc, ab, bc, t);  // point between ab and bc 
lirp(bccd, bc, cd, t);  // point between bc and cd 
lirp(dest, abbc, bccd, t); // point on the bezier-curve 

} 

void Draw() { 
glClear(GL_COLOR_BUFFER_BIT); 
glColor3f(1.0, 1.0, 1.0); 
glPointSize(20); 

point a = { 700, 100 }; 
point b = { 650, 20 }; 
point c = { 600, 180 }; 
point d = { 550, 100 }; 

for (int i = 0; i<1000; ++i) //should plot 1000 points within the control polygons. 
{ 
    point p; 
    float t = static_cast<float>(i)/999.0; 
    bezier(p, a, b, c, d, t); 
    float p_x = p.x; 
    float p_y = p.y; 
    printf("%f %f\n", p_x, p_y); 
    glBegin(GL_POINTS); 
    glVertex3f(p_x, p_y, 0.0); 
    glEnd(); 
    glutSwapBuffers(); 
} 

} 

void Timer(int Unused) 
{ 
glutPostRedisplay(); 
glutTimerFunc(20, Timer, 0); 
} 



void Init() { 
glClearColor(0.0, 0.0, 0.0, 0.0); 
glMatrixMode(GL_PROJECTION); 
glLoadIdentity(); 
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); 
} 

int main(int iArgc, char** cppArgv) { 
glutInit(&iArgc, cppArgv); 
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); 
glutInitWindowSize(800, 600); 
glutInitWindowPosition(200, 100); 
glutCreateWindow("Animation Test"); 
Init(); 
glutDisplayFunc(Draw); 
Timer(0); 
glutMainLoop(); 
return 0; 
} 
+0

*笑*这贝塞尔代码来自我的旧网站:http://cubic.org/docs/bezier.htm什么从过去的爆炸。 –

+0

哦!感谢您让我了解曲线近似值。这是非常好的解释。 – 2bit

您正在设置的投影量为glOrtho(),仅为1x1。如果你想看到你的曲线(其尺寸是几百个单位),你需要扩展它。

此外,不要glutSwapBuffers(),直到你的for循环之后;否则你最终只能看到一半的点数。您还应该将glBegin()/glEnd()放在循环之外。

+0

好吧,但我还可以用什么来代替glOrtho()?贝塞尔函数只返回曲线的“x”和“y”坐标;它不是简单的2D绘图功能吗? – 2bit

+0

'glOrtho'很好。这是你对'glOrtho'的争论。 – Sneftel

+0

万岁!有效。我并不十分清楚glOrtho接受的价值范围。将我的windowsize维度传递给右边的参数和顶层的参数确实有效!谢谢你解释! :D – 2bit