关于python:Pygame平台游戏的敌人运动

Pygame platformer enemy movement

我正在开发一个平台游戏,试图使我的敌人来回移动一定距离。基本上,我需要找到一种方法来将dis增加到某个数字,将其减小回零,然后再次将其增加回相同的数字。它需要无限期地执行此操作。现在,它增加到10,然后保持在那里。任何帮助将非常感激。 (注意:此代码只是一个测试版本,其中删除了所有"自我"。)

1
2
3
4
5
6
7
8
9
10
11
12
speed  = 1
dis = 0

while True:
    if speed > 0:
        dis += 1
    if dis > 10:
        speed = -1
        dis -= 1            
    if dis < 0:
        speed = 1
    print(dis)


您可以使用

1
2
3
4
5
6
7
8
9
10
speed  = 1
dis = 0

while True:
    dis += speed

    if dis >= 10:
        speed = -1
    elif dis <= 0:
        speed = 1

dis += speed可以在if/elif之前或if/elif之后,以获得预期结果。

或者甚至可以使用speed = -speed更改方向

1
2
3
4
5
6
7
8
speed  = 1
dis = 0

while True:
    dis += speed

    if dis <= 0 or dis >= 10:
        speed = -speed


您为什么不尝试将其分解?根据当前距离,设置速度。然后根据当前速度,增加或减少距离。

1
2
3
4
5
6
7
8
9
10
speed  = 1
dis = 0

while True:
    if dis >= 10:
        # Set speed
    if dis <= 0:
        # Set speed

    # Based on speed, increment or decrement distance


我知道了:)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
speed  = 1
dis = 0



while True:
    if speed >= 0:
        dis += 1
    if dis >= 10:
        speed = -1            
    if speed <= 0:
        dis -= 1
    if dis <= 0:
        speed = 1
    print(dis)


您可以只检查对象是否在该区域之外,然后反转速度。 pygame.Rect具有很多属性,例如leftright,在这里可能会有所帮助。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray13')
BLUE = pg.Color('dodgerblue1')

rect = pg.Rect(300, 200, 20, 20)
distance = 150
speed = 1

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    # Check if the rect is outside of the specified
    # area and if it's moving to the left or right.
    if (rect.right > 300+distance and speed > 0
            or rect.left < 300 and speed < 0):
        speed *= -1  # Invert the speed.
    # Add the speed to the rect's x attribute to move it.
    rect.x += speed

    # Draw everything.
    screen.fill(BG_COLOR)
    pg.draw.rect(screen, BLUE, rect)
    pg.display.flip()
    clock.tick(60)

pg.quit()