我正嘗試將汽車直線移動。 我所擁有的是該行的起點和終點。直線移動車輛
這是我到目前爲止
glTranslated(x, y, z);
glRotated(angle * 180/PI, 0, 1, 0);
glColor3d(0.1, 0.1, 0.4);
glutSolidCube(40); // imagine that this is a car
x += speed * sin(angle + PI/2);
z += speed * cos(angle + PI/2);
的角度由
double dist = sqrt((double)(x2-x1)*(x2-x1) + (double)(y2-y1)*(y2-y1));
int deltaX = abs(x2-x1);
angle = PI - acos(deltaX/dist)
該解決方案獲得試過偶爾的工作,如果1點是點2的左側,只有一輛車正在移動。 如果我試圖同時移動幾輛汽車,則只有一輛汽車如預期的那樣移動。然而,其他人似乎都有自己的意志......
所以......
- 什麼我需要做的,使所有的汽車駕駛起來呢?
- 如何正確計算角度? (無論在哪裏是起點)
重要提示:汽車在行駛在平坦的xz平面(Y = 0)
編輯:
這是我的汽車類(此刻)
#include "glut.h"
#include <math.h>
#include "Car.h"
Car::Car(double x, double y, double z, double speed, double angle)
{
this->x = x;
this->y = y;
this->z = z;
this->speed = speed;
this->angle = angle;
}
void Car::draw3D()
{
glTranslated(x, y, z);
glRotated(angle * 180/3.14, 0, 1, 0);
glColor3d(0.1, 0.1, 0.4);
glutSolidCube(40);
x += speed * sin(angle + 1.57);
z += speed * cos(angle + 1.57);
}
我這是怎麼構建一個汽車
for(vector<Road*>::iterator it = roads.begin(); it != roads.end(); ++it) {
int x1 = (*it)->x1;
int y1 = (*it)->y1;
int x2 = (*it)->x2;
int y2 = (*it)->y2;
double mangle = -atan2((double)y2-y1, (double)x2-x1);
cars.push_back(new Car(x1-GRID_SIZE/2, 0, y1-GRID_SIZE/2, 5, mangle));
}
而且這是我畫的所有汽車
for(vector<Car*>::iterator it = cars.begin(); it != cars.end(); ++it) {
(*it)->draw3D();
}
在draw3d()的開頭放置'glPushMatrix();',在'glPopMatrix();'結尾。然後再試一次。 –
是的。只是想到了這一點。現在它正在工作。謝謝您的幫助。 –
好。最後一件事:GLUT已被棄用,並且真的很舊,您可以考慮使用[GLEW](http://glew.sourceforge.net/)。 –