第一個程式
你的第一個程式會讓機器人往前走,並在牆前停下來。它很短,但具備了每個程式都需要的一切。
from controller import Robot
robot = Robot()timeStep = int(robot.getBasicTimeStep())
# Get the devices of the starter robot by nameleftWheel = robot.getDevice("left wheel motor")rightWheel = robot.getDevice("right wheel motor")frontDist = robot.getDevice("frontDist")
# Sensors must be enabled before usefrontDist.enable(timeStep)
# Let the wheels turn without limit, and start driving forwardleftWheel.setPosition(float("inf"))rightWheel.setPosition(float("inf"))leftWheel.setVelocity(3.0)rightWheel.setVelocity(3.0)
# The main loop: each step, the simulation advances by timeStep millisecondswhile robot.step(timeStep) != -1: distance = frontDist.getValue() print("Distance to the wall in front:", round(distance, 3), "m")
if distance < 0.05: # Closer than 5 cm: stop leftWheel.setVelocity(0) rightWheel.setVelocity(0) print("Wall reached!") break#include <iostream>#include <cmath>#include <webots/Robot.hpp>#include <webots/Motor.hpp>#include <webots/DistanceSensor.hpp>
using namespace webots;using namespace std;
int main() { Robot *robot = new Robot(); int timeStep = (int)robot->getBasicTimeStep();
// Get the devices of the starter robot by name Motor *leftWheel = robot->getMotor("left wheel motor"); Motor *rightWheel = robot->getMotor("right wheel motor"); DistanceSensor *frontDist = robot->getDistanceSensor("frontDist");
// Sensors must be enabled before use frontDist->enable(timeStep);
// Let the wheels turn without limit, and start driving forward leftWheel->setPosition(INFINITY); rightWheel->setPosition(INFINITY); leftWheel->setVelocity(3.0); rightWheel->setVelocity(3.0);
// The main loop: each step, the simulation advances by timeStep milliseconds while (robot->step(timeStep) != -1) { double distance = frontDist->getValue(); cout << "Distance to the wall in front: " << distance << " m" << endl;
if (distance < 0.05) { // Closer than 5 cm: stop leftWheel->setVelocity(0); rightWheel->setVelocity(0); cout << "Wall reached!" << endl; break; } }
delete robot; return 0;}- 建立機器人。
Robot()會把你的程式連接到模擬器中的機器人。 - 取得時間步長。 模擬以每步幾毫秒的方式前進。
getBasicTimeStep()會提供這個世界的步長。 - 取得裝置。 每個馬達和感測器都依名稱取得。這些名稱就是你在組裝機器人時為它們取的名字。
- 啟用感測器。 感測器在啟用之前不會提供任何數值。時間步長會告訴它多久更新一次。
- 迴圈。
robot.step(timeStep)會讓模擬前進一步,並在模擬結束時回傳 -1。機器人做的每一件事都在這個迴圈中發生。
- 把程式儲存為
hello.py。 - 開啟
game/worlds/mapping_example_1.wbt,用右邊的 LOAD 按鈕載入入門機器人。 - 用左邊的 LOAD 按鈕載入
hello.py,然後按下開始。
機器人會往前走,Webots 主控台會顯示它與前方牆壁的距離,直到機器人停下來。如果你看到的是錯誤訊息,請查看疑難排解。
- 把速度從
3.0改成6.0。接近牆壁時會發生什麼事? - 讓機器人在 10 cm 而不是 5 cm 處停下來。
- 也用
robot.getTime()印出時間。
接下來,在移動中學習如何前進和轉彎。
