Airsim中利用键盘控制无人机飞行
Airsim中利用键盘控制无人机飞行
直接上源代码:
import keyboard
import airsim
client = airsim.MultirotorClient()
client.confirmConnection()
def control(x):
w = keyboard.KeyboardEvent('down', 28, 'w')
s = keyboard.KeyboardEvent('down', 28, 's')
a = keyboard.KeyboardEvent('down', 28, 'a')
d = keyboard.KeyboardEvent('down', 28, 'd')
up = keyboard.KeyboardEvent('down', 28, 'up')
down = keyboard.KeyboardEvent('down', 28, 'down')
left = keyboard.KeyboardEvent('down', 28, 'left')
right = keyboard.KeyboardEvent('down', 28, 'right')
enter = keyboard.KeyboardEvent('down', 28, 'enter')
k = keyboard.KeyboardEvent('down', 28, 'k')
l = keyboard.KeyboardEvent('down', 28, 'l')
if x.event_type == 'down' and x.name == w.name:
#前进
client.moveByVelocityBodyFrameAsync(3, 0, 0, 0.5)
print("你按下了 "+x.name+" 键 ")
elif x.event_type == 'down' and x.name == s.name:
#后退
client.moveByVelocityBodyFrameAsync(-3, 0, 0, 0.5)
print("你按下了 " + x.name + " 键")
elif x.event_type == 'down' and x.name == a.name:
#左移
client.moveByVelocityBodyFrameAsync(0, -2, 0, 0.5)
print("你按下了 " + x.name + " 键")
elif x.event_type == 'down' and x.name == d.name:
#右移
client.moveByVelocityBodyFrameAsync(0, 2, 0, 0.5)
print("你按下了 " + x.name + " 键")
elif x.event_type == 'down' and x.name == up.name:
#上
client.moveByVelocityBodyFrameAsync(0, 0, -0.5, 0.5)
print("你按下了 " + x.name + " 键")
elif x.event_type == 'down' and x.name == down.name:
#下
client.moveByVelocityBodyFrameAsync(0, 0, 0.5, 0.5)
print("你按下了 " + x.name + " 键")
elif x.event_type == 'down' and x.name == left.name:
#左转
client.rotateByYawRateAsync(-20, 0.5)
print("你按下了 " + x.name + " 键")
elif x.event_type == 'down' and x.name == right.name:
#右转
client.rotateByYawRateAsync(20, 0.5)
print("你按下了 " + x.name + " 键")
elif x.event_type == 'down' and x.name == enter.name:
#enter
print("你按下了 " + x.name + " 键")
elif x.event_type == 'down' and x.name == k.name:
# get control
client.enableApiControl(True)
print("get control")
# unlock
client.armDisarm(True)
print("unlock")
client.takeoffAsync().join()
print("takeoff")
print("你按下了 " + x.name + " 键")
elif x.event_type == 'down' and x.name == l.name:
#降落
client.landAsync().join()
print("land")
# lock
client.armDisarm(False)
print("lock")
# release control
client.enableApiControl(False)
print("release control")
print("你按下了 " + x.name + " 键")
else: #没有按下按键
client.moveByVelocityBodyFrameAsync(0, 0, 0, 0.5).join()
client.hoverAsync().join() # 第四阶段:悬停6秒钟
print("stop 悬停")
#当监听的事件为enter键,且是按下的时候
keyboard.hook(control)
keyboard.wait()