Created
September 14, 2024 13:43
-
-
Save yoniLavi/bbcede61fd7f5f57af0946bde2780bc7 to your computer and use it in GitHub Desktop.
A slightly simplified version of the Webots collision detection example at https://cyberbotics.com/doc/guide/tutorial-4-more-about-controllers?tab-language=python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from controller import Robot, DistanceSensor, Motor | |
TIME_STEP = 64 | |
SPEED = 3.14 | |
PROXIMITY_THRESHOLD = 80 | |
robot = Robot() | |
def setup_sensor(device_id): | |
sensor = robot.getDevice(f"ps{device_id}") | |
sensor.enable(TIME_STEP) | |
return sensor | |
def obstacle_close(sensors): | |
return any(s.getValue() > PROXIMITY_THRESHOLD for s in sensors) | |
right_sensors = [setup_sensor(i) for i in range(3)] | |
left_sensors = [setup_sensor(i) for i in range(5, 8)] | |
leftMotor = robot.getDevice('left wheel motor') | |
rightMotor = robot.getDevice('right wheel motor') | |
leftMotor.setPosition(float('inf')) | |
rightMotor.setPosition(float('inf')) | |
while robot.step(TIME_STEP) != -1: | |
if obstacle_close(left_sensors): # turn right | |
leftMotor.setVelocity(SPEED) | |
rightMotor.setVelocity(-SPEED) | |
elif obstacle_close(right_sensors): # turn left | |
leftMotor.setVelocity(-SPEED) | |
rightMotor.setVelocity(SPEED) | |
else: # go straight | |
leftMotor.setVelocity(SPEED) | |
rightMotor.setVelocity(SPEED) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment