C++、Java 与 Python 为面向对象语言,Webots 在其上提供了面向对象的 API 层,建立在 C API 之上,包含约 25 个类与 200 个方法。
WbDeviceTag)wb_* 函数族(实现于 libcontroller)
命名约定:C++/Java/Python 的类与方法名称直接对应 C API。
例如 C 函数 double wb_distance_sensor_get_value(WbDeviceTag tag)
在三种语言中对应类 DistanceSensor 的 getValue() 方法,且通常移除了 WbDeviceTag 参数。
控制器应从 Robot 或 Supervisor 继承:当节点的 supervisor 字段为 TRUE 时使用 Supervisor;否则使用 Robot。
Robot 的方法(如 step()、getLED())worldReload())run() 主循环,并在其中调用 Robot.step()getDistanceSensor()、getTouchSensor() 等方法获取设备实例;无 WbDeviceTag#include <webots/Robot.hpp>
#include <webots/LED.hpp>
#include <webots/DistanceSensor.hpp>
using namespace webots;
int main() {
Robot robot;
int timeStep = (int)robot.getBasicTimeStep();
LED* led = robot.getLED("ledName");
DistanceSensor* distanceSensor = robot.getDistanceSensor("distanceSensorName");
distanceSensor->enable(timeStep);
while (robot.step(timeStep) != -1) {
double val = distanceSensor->getValue();
// TODO: 处理传感器数据
led->set(1);
}
return 0;
}
import com.cyberbotics.webots.controller.*;
public class MyController {
public static void main(String[] args) {
Robot robot = new Robot();
int timeStep = (int)Math.round(robot.getBasicTimeStep());
LED led = robot.getLED("my_led");
DistanceSensor distanceSensor = robot.getDistanceSensor("my_distance_sensor");
distanceSensor.enable(timeStep);
while (robot.step(timeStep) != -1) {
double val = distanceSensor.getValue();
// TODO: 处理传感器数据
led.set(1);
}
}
}
from controller import Robot
robot = Robot()
timestep = int(robot.getBasicTimeStep())
led = robot.getDevice('ledName')
distanceSensor = robot.getDevice('distanceSensorName')
distanceSensor.enable(timestep)
while robot.step(timestep) != -1:
val = distanceSensor.getValue()
# TODO: 处理传感器数据
led.set(1)