Search code examples
anylogic

How to set the preferred speed of car in Anylogic?


I am trying to create a traffic congestion dynamically by reducing the speed of the car.

for (Car car :cars) { 
  car = cars.get(uniform_discr(0,cars.size()-1));
  double currentSpeed = car.getSpeed(); // in meters per second

  // Define a random congestion factor (e.g., between 0.8 and 1.0)
  double minCongestionFactor = 0.8;
  double maxCongestionFactor = 1.0;
  double randomCongestionFactor = minCongestionFactor + Math.random() * (maxCongestionFactor - minCongestionFactor);

  // Calculate the adjusted speed
  double adjustedSpeed = currentSpeed * randomCongestionFactor;

  // Set the preferred speed for the car
  car.setPreferredSpeed(adjustedSpeed);
}

But I am getting the error,

Description: The method setPreferredSpeed(double) is undefined for the type Car. Location: updated_Model_Trafic_flow_on_dynamic_ pricing2/Main/event1 - Event


Solution

  • Make sure your Car agent type is actually defined to be a car: enter image description here

    Only then does code-complete actually let you write this method: enter image description here

    PS: Always use code-complete, never type code yourself. This way, you always know upfront if a method is actually available or not