I'm trying to move a car in a straight line.
What I have is the starting and ending points of the line.
This is what I've tried so far
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);
The angle is received by
double dist = sqrt((double)(x2-x1)*(x2-x1) + (double)(y2-y1)*(y2-y1));
int deltaX = abs(x2-x1);
angle = PI - acos(deltaX/dist)
This solution works occasionally if point 1 is to the left of point 2 and only one car is moving.
If I try to move several cars simultaneously only one of the cars moves as expected. The others however seem to have a will of their own...
So...
- What do I need to do to make all of the cars drive together?
- How Should I calculate the angle properly? (regardless of where is the starting point)
Important Note: The car is moving on a flat xz plane (y=0)
EDIT:
This is my car class (at the moment)
#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);
}
This is how i construct a car
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));
}
And this is how I draw all the cars
for(vector<Car*>::iterator it = cars.begin(); it != cars.end(); ++it) {
(*it)->draw3D();
}