我已经做到了这一点,当用户点击WASD时,它会使smooth_x或smooth_y变为5,以便不断添加到x或y坐标以模拟运动。
但是我有一个问题,如果用户按住A然后他们同时点击D,它会使smooth_x为0,导致用户留在原地。
EG用户点击D(smooth_x = 5)用户点击A(smooth_x = -5)用户持有D然后持有A然后放开D导致smooth_x为= 0导致用户停止移动我没有&#39不想要。在这种情况下,smooth_x应该是= -5
while gameloop == True:
num_scraps = 0
fps.tick(60) #Sets FPS to 60
for event in pygame.event.get(): #Checks each event
if event.type == pygame.QUIT: #If one of the events are quit (when the user clicks the X in the top right corner) the window closes
pygame.quit()
if event.type == pygame.KEYUP:
print(event)
#If the user stop pressing one of the arrow keys it sets all the smooth values to 0 so it stops increasing the x or y coordinate
if event.key == pygame.K_w:
smoothy = 0
if event.key == pygame.K_s:
smoothy = 0
if event.key == pygame.K_a:
smoothx = 0
if event.key ==pygame.K_d:
smoothx = 0
if event.type == pygame.KEYDOWN: #Checks for a keypress
print(event)
if event.key == pygame.K_w:
smoothy -= 5 #reduces the y by 5 so player moves up
if event.key == pygame.K_s:
smoothy += 5 #increases the y by 5 so player moves down
if event.key == pygame.K_a:
smoothx -= 5 #reduces the x by 5 so player moves left
if event.key == pygame.K_d:
smoothx += 5 #increases the x by 5 so player moves right
答案 0 :(得分:0)
使用KEYUP
中的add / substract,就像在KEYDOWN
中一样,但符号相反。
if event.type == pygame.KEYUP:
print(event)
if event.key == pygame.K_w:
smoothy += 5
if event.key == pygame.K_s:
smoothy -= 5
if event.key == pygame.K_a:
smoothx += 5
if event.key ==pygame.K_d:
smoothx -= 5
if event.type == pygame.KEYDOWN: #Checks for a keypress
print(event)
if event.key == pygame.K_w:
smoothy -= 5 #reduces the y by 5 so player moves up
if event.key == pygame.K_s:
smoothy += 5 #increases the y by 5 so player moves down
if event.key == pygame.K_a:
smoothx -= 5 #reduces the x by 5 so player moves left
if event.key == pygame.K_d:
smoothx += 5 #increases the x by 5 so player moves right
答案 1 :(得分:0)
我通常以这种方式处理运动:如果按下一个键,我将x和y速度设置为所需的值,并更新主循环中的位置。为了停止左右移动,我还要检查角色是向左移动还是向右移动smoothx > 0
,然后再将值设置为0.如果按左边两个角色,角色将不会停止和右键同时。
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
smoothy = -5
elif event.key == pygame.K_s:
smoothy = 5
elif event.key == pygame.K_a:
smoothx = -5
elif event.key == pygame.K_d:
smoothx = 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_w and smoothy < 0:
smoothy = 0
elif event.key == pygame.K_s and smoothy > 0:
smoothy = 0
elif event.key == pygame.K_a and smoothx < 0:
smoothx = 0
elif event.key ==pygame.K_d and smoothx > 0:
smoothx = 0
对于上下运动而言,这并不重要,因为同时上下都很难同时按下,但当然你也可以检查一下这一点。