我正在Pygame中构建一个游戏,其中涉及使用箭头键移动红色矩形(玩家)。我已经让玩家使用箭头键移动(箭头键控制速度,输入键确认移动),但是我需要能够限制玩家每转的移动量。我需要这样做,以便新的速度/位置最多只能将上/下和上下左右分别设为20像素(20像素表示两次按箭头键)。
当前,玩家按照箭头键设置的速度移动,但是速度与箭头键一起无限期地增加/减少。一旦需要在任一方向(向上/向下,向左/向右)上最多按两次箭头键,我就需要停止更改。
以下是控制速度的代码:
if event.type == pygame.KEYDOWN:
if p1_turn:
if event.key == pygame.K_RIGHT:
p1_velocity_x += 10
if event.key == pygame.K_LEFT:
p1_velocity_x -= 10
这是确认更改的代码(实际上是在移动播放器):
if event.key == pygame.K_RETURN:
if p1_turn:
p1.y += p1_velocity_y
p1.x += p1_velocity_x
p1_turn = False
p2_turn = True
如前所述,应该有某种机制来阻止速度从原始x速度和原始y速度超过20px增加/减少。
答案 0 :(得分:1)
只需使用if statements
:
original_vel_x = 0
if p1_turn:
if event.key == pygame.K_RIGHT:
if p1_velocity_x <= original_vel_x + 20: # I used <= in case it's being increased with floats
p1_velocity_x += 10
else:
print('Cannot Move')
答案 1 :(得分:0)
import pygame
...
#Change those to whatever you want.
maximux_x = 20
minimum_x = 10
#This holds the players velocity on x.
p1_velocity_x = 0
def ChangeVelocity(change):
global p1_velocity_x
#cacl new x.
new_x = p1_velocity_x + change
if new_x < minimum_x:
return
if new_x > maximux_x:
return
#Change is inside the restrictions, so apply the change.
p1_velocity_x += change
...
if event.type == pygame.KEYDOWN:
if p1_turn:
if event.key == pygame.K_RIGHT:
ChangeVelocity(10)
if event.key == pygame.K_LEFT:
ChangeVelocity(-10)
为了更好地控制,您应该使用类创建子画面对象。一个示例如下所示:
import pygame
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
class Player:
def __init__(self):
self.pos = Vector(0,0)
self.maxX = 20
self.maxY = 10
def MoveOnX(self, change):
global p1_velocity_x
#cacl new x.
new_x = self.pos.x + change
if new_x < self.maxX:
return
if new_x > self.maxY:
return
#Change is inside the restrictions, so apply the change.
self.pos.x += change
#Create a new player and spawn him at (5,5)
player = Player()
player.pos.x = 5
player.pos.y = 5
if event.type == pygame.KEYDOWN:
if p1_turn:
if event.key == pygame.K_RIGHT:
player.MoveOnX(10)
if event.key == pygame.K_LEFT:
player.MoveOnX(-10)