確定繼承人我的計劃:翻譯在OpenGL的對象上不同坡度
#include<windows.h>
#include<gl/gl.h>
#include<gl/glu.h>
#include<glut.h>
#include<math.h>
#include<stdlib.h>
#include <stdio.h>
float points[6][2];
int count=0;
int moving=0;
float test=1.0;
GLfloat x=1.0, y=1.0;
GLint windW=680,windH=500;
void myDisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
static void drawRoad(int a1, int b1, int a2, int b2){
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_POLYGON);
glVertex2f(a1, b1); glVertex2f(a2, b2); glVertex2f(a2, b2-40); glVertex2f(a1, b1-40);
glEnd();
}
static void drawCar(int a, int b){
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POLYGON);
glVertex2f(a-30, b); glVertex2f(a, b+20); glVertex2f(a+30, b); glVertex2f(a, b-20);
glEnd();
}
static void myMouse(int button,int state,int x,int y)
{
if(button==GLUT_LEFT_BUTTON&&state==GLUT_DOWN){
points[count][0]=x;
points[count][1]=windH-y;
count = count+1;
}
if(count==2){
drawRoad(0.0, points[0][1], points[1][0], points[1][1]);
}
if(count==4){
drawRoad(points[2][0], points[2][1], 0.0, points[3][1]);
}
if(count==5){
drawCar(points[4][0], points[4][1]);
}
if(count==6){
drawCar(points[5][0], points[5][1]);
moving=1;
}
glFlush();
}
void myInit()
{
glClearColor(1.0,1.0,1.0,0.0);
glColor3f(0.1,0.5,0.7);
glPointSize(2.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluOrtho2D(0.0,640.0,0,500.0);
}
void main(int argc,char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(680,500);
glutInitWindowPosition(10,10);
glutCreateWindow("Assignment 3");
myInit();
glutMouseFunc(myMouse);
glutDisplayFunc(myDisplay);
glutMainLoop();
}
我的程序的要點:我讓用戶在鼠標點擊指定2條高速公路,然後我讓用戶指定2輛各高速公路。一旦放置第二輛汽車,我需要讓汽車在各自的高速公路上行駛,我需要檢測是否有碰撞。我沒有在碰撞部分工作,但我的問題是讓汽車移動。我將使用以下的汽車沿着高速公路每一個的斜率線翻譯:
float m = (y2 - Y1)/(float)(x2 - x1);
if (fabs(m) <= 1) //if abs(slope) is between 0 and 1
{
//decide how to draw the line (start at x1 or x2?)
if (x1 <= x2)
{
x=x+0.5;
y = (y + m);
}
else
{
x=x-0.5;
y = (y - m);
}
}
else //if abs(slope) is > 1
{
//decide how to draw the line (start at y1 or y2?)
if (Y1 <= y2)
{
y=y+0.5;
x = (x + (1/m));
}
else
{
y=y-0.5;
x = (x - (1/m));
}
}
glTranslatef(x, y, 0.0);
X1,Y1,X2和Y2是我使用的是從各高速公路的點來確定的斜率和x和y設置爲1.0開始。
我知道這個代碼工作在不同的斜坡上翻譯,但我的問題是我不太確定我應該把這部分放到我的代碼中。我試圖把它放在drawCar函數中,但後來我一旦我到達代碼的那一點,會得到一個錯誤...任何想法?