Domanda

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...

  1. What do I need to do to make all of the cars drive together?
  2. 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();
}
È stato utile?

Soluzione

For the angle it is probably easier to use

angle = atan2(y2-y1, x2-x1);

atan2 computes not only the arctangent for your vector, but also takes care of the nasty case-handling whenever your angle would not be definite.

(Remember that cosine/sine are periodic with period pi, so just using a delta-value will result in two possible angles, i.e. (1,1) and (-1,-1) will both result in the angle 45°).

Maybe this does solve your problem of the cars not driving together. If not check that every car gets an own angle assigned to it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top