最初のプログラム
最初のプログラムは、ロボットを前進させ、壁の手前で止めます。短いプログラムですが、どのプログラムにも必要なものがすべて入っています。
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 ステップ進め、シミュレーションが終わると -1 を返します。ロボットのすべての動作は、このループの中で行われます。
- プログラムを
hello.pyとして保存します。 game/worlds/mapping_example_1.wbtを開き、右側の LOAD ボタンでスターターロボットを読み込みます。- 左側の LOAD ボタンで
hello.pyを読み込み、スタートを押します。
ロボットが前進し、止まるまでの間、正面の壁までの距離が Webots のコンソールに表示されます。代わりにエラーが表示された場合は、トラブルシューティングを確認してください。
試してみよう
Section titled “試してみよう”- 速度を
3.0から6.0に変えてみましょう。壁の近くで何が起こりますか? - 5 cm ではなく 10 cm で止まるようにしてみましょう。
robot.getTime()で時間も表示してみましょう。
次は、移動で走行と旋回を学びましょう。
