package prey;
import java.util.Random;
public class AvoidObstacle extends Behavior {
    private Random rand = new Random();
    private final int detectDistance = 15; // Defines the maximum distance (in cm) for this behavior to react. 
    public AvoidObstacle(String name, int priority) {
        super(name, priority);
    public int getMotivation() {
        // Saves the measurement of the ultrasonic sensor. 
        int distance = Sensors.getUltraSonicDistance();
        if (isRunning()) {
            // If the robot is avoiding an obstacle the motivations is at least 50. 
            // This makes sure that it takes something important to take precedence. 
            return (int) Math.max(50, (detectDistance-distance)*(100/detectDistance));
        } else {
            return (int) Math.max(0, (detectDistance-distance)*(100/detectDistance));
    public void action() throws InterruptBehaviorException {
        // Stops the motors and resets the head. 
        int headDirection = HeadTurner.getCurrentPosition();
        // The power used to avoid obstacles. 
        int power = 80;
        // Asynchronous sound call. 
        // The back off depends upon the direction of the head. 
        switch (headDirection) {
            case HeadTurner.CENTER:
                // If the head was centered the robot makes a backwards turn. 
                Mover.turnInRandomdirection(power, true);
                delay(1000 + rand.nextInt(500));
            case HeadTurner.LEFT:
                // If the head was turning left, back off to the left. 
                Mover.backward(0, power);
                delay(1000 + rand.nextInt(500));
            case HeadTurner.RIGHT:
                // If the head was turning right, back off to the right. 
                Mover.backward(power, 0);
                delay(1000 + rand.nextInt(500));
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License