コンテンツにスキップ
日本語

位置センサー

位置センサー(GPS)は、ロボットの位置を メートル 単位で返します。スターターロボットでは gps という名前です。壁のトークンを報告するには位置センサーが必要で、計画的に探索するときにもとても役立ちます。

getValues() は [x, y, z] を返します。X と Z が水平方向で、Y が垂直方向なので、迷路内の位置には X と Z を使います。

水平面の X 軸と Z 軸、垂直方向の Y 軸

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
gps = robot.getDevice("gps")
gps.enable(timeStep)
while robot.step(timeStep) != -1:
x, y, z = gps.getValues() # In meters. X and Z are horizontal, Y is vertical.
print("x:", round(x, 3), "z:", round(z, 3))

GPS には数ミリメートルのノイズがあるので、ロボットが止まっていても値は少しずつ変わります。位置が完全に一致するかどうかで比較してはいけません。

このプログラムは、ロボットがスタート地点からタイル半分の距離に達するまで前進します。

from controller import Robot
import math
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
gps = robot.getDevice("gps")
gps.enable(timeStep)
leftWheel = robot.getDevice("left wheel motor")
rightWheel = robot.getDevice("right wheel motor")
leftWheel.setPosition(float("inf"))
rightWheel.setPosition(float("inf"))
robot.step(timeStep) # Step once, so that the GPS has a value
startX, _, startZ = gps.getValues()
leftWheel.setVelocity(3.0)
rightWheel.setVelocity(3.0)
while robot.step(timeStep) != -1:
x, _, z = gps.getValues()
distance = math.sqrt((x - startX) ** 2 + (z - startZ) ** 2)
print("Distance from the start:", round(distance, 3), "m")
if distance > 0.06: # Half a tile
leftWheel.setVelocity(0)
rightWheel.setVelocity(0)
break