我需要编写代码来控制带有操纵杆的两轮机器人的运动。我已经写了将其向前,向后移动(asx _y),转向(asx _z)以及随着一个引擎的运动而转向(asx _x)的条件。现在我们需要以某种方式为其沿对角线移动创建条件,以便在激活y和x或y轴时,它同时获取轴的两个值并沿对角线精确移动。非常感谢你。对不起,我的英语
import socket
import pygame
import time
pygame.init()
pygame.display.set_mode((640, 480))
rc_socket = socket.socket()
try:
rc_socket.connect(('192.168.1.102', 1234)) # connect to robot
except socket.error:
print("could not connect to socket")
joystick_count = pygame.joystick.get_count()
for i in range(joystick_count):
joystick = pygame.joystick.Joystick(i)
joystick.init()
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
u1 = -1.0
u2 = 1.0
print("turn left: ({},{})".format(u1, u2))
elif event.key == pygame.K_RIGHT:
u1 = 1.0
u2 = -1.0
print("turn right: ({},{})".format(u1, u2))
elif event.key == pygame.K_UP:
u1 = -1.0
u2 = -1.0
print("forward: ({},{})".format(u1, u2))
elif event.key == pygame.K_DOWN:
u1 = 1.0
u2 = 1.0
print("forward: ({},{})".format(u1, u2))
rc_socket.send('({},{})\n'.format(u1, u2).encode())
`enter code here`elif event.type == pygame.KEYUP:
u1 = 0
u2 = 0
print("key released, resetting: ({},{})".format(u1, u2))
rc_socket.send('({},{})\n'.format(u1, u2).encode())
if joystick:
asix_x = joystick.get_axis(2)
asix_y = joystick.get_axis(1)
asix_z = joystick.get_axis(4)
if asix_x < -0.12:
u1 = -asix_x
u2 = 0
rc_socket.send('({},{})\n'.format(u1, u2).encode())
time.sleep(0.1)
elif asix_x and asix_y > 0.15:
u1 = 0
u2 = asix_x
rc_socket.send('({},{})\n'.format(u1, u2).encode())
pygame.time.delay(100)
u1 = -asix_y
u2 = -asix_y
rc_socket.send('({},{})\n'.format(u1, u2).encode())
time.sleep(0.1)
elif asix_x > 0.12:
u1 = 0
u2 = asix_x
rc_socket.send('({},{})\n'.format(u1, u2).encode())
time.sleep(0.1)
elif asix_y < -0.12:
u1 = -asix_y
u2 = -asix_y
rc_socket.send('({},{})\n'.format(u1, u2).encode())
time.sleep(0.1)
elif asix_y > 0.12:
u1 = -asix_y
u2 = -asix_y
rc_socket.send('({},{})\n'.format(u1, u2).encode())
time.sleep(0.1)
elif asix_z > 0.12:
u1 = asix_z
u2 = -asix_z
rc_socket.send('({},{})\n'.format(u1, u2).encode())
time.sleep(0.1)
elif asix_z < -0.12:
u1 = asix_z
u2 = -asix_z
rc_socket.send('({},{})\n'.format(u1, u2).encode())
time.sleep(0.1)
else:
u1 = 0.0
u2 = 0.0
rc_socket.send('({},{})\n'.format(u1, u2).encode())
time.sleep(0.1)