第一个程序
你的第一个程序会让机器人向前行驶,并在墙前停下。它很短,但包含了每个程序都需要的所有内容。
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()打印时间。
接下来,在移动中学习如何行驶和转向。
