This is part of a simulation of vehicles slowing down before they hit the next car, this function is called at every timeout of a timer in my main class.
The issue that I am having is that the vehicles are coming to a stop in front of the car furthest from them rather than the one closest to them. And the car at the front of the lane is stopping altogether.
The first part of the function is trying to find the smallest gap between any two cars in the same lane, and then storing which car this is. This is then used in the second part of the function.
The second part of the function, after the j loop, is the part that tells the car to either speed up or slow down depending on how close it is to the car in front.
I'm not sure why the cars are responding to the wrong ones in front?
void Road::CheckAhead()
{
int carahead = 0;
for(int i = 0; i < fVectorOfVehicles.size(); i++){
for(int j = 0; j < fVectorOfVehicles.size(); j++){
cout << j << endl;
if(fVectorOfVehicles[i]->GetPosition().GetY() == fVectorOfVehicles[j]->GetPosition().GetY()
&& fVectorOfVehicles[i]->GetPosition().GetX() < fVectorOfVehicles[j]->GetPosition().GetX()){
//Only take into account the vehicles in the same lane and the vehicles ahead
double smallest = 1000;
double space = fVectorOfVehicles[j]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX();
//Find difference between vehicle j and i
if(space < smallest){
//Only done if the difference between current two vehicles is smaller than others
smallest = space;
carahead = j;
}
//Find the car ahead of [i]
}
}
if(fVectorOfVehicles[carahead]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX() < 70.0){
//If vehicle is too close the one ahead, slow down
fVectorOfVehicles[i]->SetValue("Velocity", (fVectorOfVehicles[i]->GetVelocity() - 0.5));
if(fVectorOfVehicles[carahead]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX() < 30.0){
fVectorOfVehicles[i]->SetValue("Velocity", (fVectorOfVehicles[i]->GetVelocity() - 2));
}
if(fVectorOfVehicles[carahead]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX() < 10.0){
fVectorOfVehicles[i]->SetValue("Velocity", (fVectorOfVehicles[i]->GetVelocity() - 3));
}
//The closer the vehicles get, the more they break
}
if((fVectorOfVehicles[carahead]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX()) > 60.0){
fVectorOfVehicles[i]->SetValue("Velocity", (fVectorOfVehicles[i]->GetVelocity() + 0.1));
}
//If vehicle is too far from the one ahead, speed up
if(fVectorOfVehicles[carahead]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX() == 80.0){
fVectorOfVehicles[i]->SetValue("Velocity", (fVectorOfVehicles[i]->GetVelocity() + 0));
}
//If the distance is at 30, remain at the same speed
if(fVectorOfVehicles[i]->GetVelocity() < 0){
fVectorOfVehicles[i]->SetValue("Velocity", 0);
}
//Stop the vehicles from reversing
}
}
Aucun commentaire:
Enregistrer un commentaire