Pygame:让事情比 1 慢 [英] Pygame: Making things move slower than 1

查看:22
本文介绍了Pygame:让事情比 1 慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个类似 Space Invaders 的游戏,一切都很好,只是我觉得我编程的敌人移动得太快了.如果我将它们的移动速度设为 1 以下,例如 0.5,它们甚至不会移动.有什么办法可以让动作更慢吗?

I made a little Space Invaders like game, everything is good except that I feel like my enemies I programmed move too fast. If I make their movement speed under 1 such as 0.5, they won't even move. Is there a way I can make the movement even slower?

这是我的敌方单位的代码:

Here is the code for my enemy unit:

import math


WINDOW = pygame.display.set_mode((800, 900))


class Enemy (pygame.sprite.Sprite):

    def __init__(self):
        super(). __init__ ()
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((20,20))
        self.image.fill((255,0,0))
        pygame.draw.circle(self.image,(COLOUR4), (10,10),10)
        self.rect=self.image.get_rect()
        self.rect.center=(0,0)
        self.dx=2
        self.dy=1

    def update(self):
        self.rect.centery += self.dy


for i in range (100):
    enemy = Enemy()
    enemy.rect.x=random.randrange(750)
    enemy.rect.y=random.randrange(100)
    enemy_list.add(enemy)
    all_sprites_list.add(enemy)

推荐答案

问题是 pygame.Rects 只能有整数,因为它们的坐标和浮点数被截断.如果您想要浮点值作为速度,您必须将实际位置存储为一个单独的属性(或两个,如下面的第一个示例),每帧添加速度,然后将新位置分配给矩形.

The problem is that pygame.Rects can only have ints as their coordinates and floats get truncated. If you want floating point values as the velocities, you have to store the actual position as a separate attribute (or two as in the first example below), add the velocity to it every frame and then assign the new position to the rect.

class Enemy(pygame.sprite.Sprite):

    def __init__(self, pos):  # You can pass the position as a tuple, list or vector.
        super().__init__()
        self.image = pygame.Surface((20, 20))
        self.image.fill((255, 0, 0))
        pygame.draw.circle(self.image, (COLOUR4), (10, 10), 10)
        # The actual position of the sprite.
        self.pos_x = pos[0]
        self.pos_y = pos[1]
        # The rect serves as the blit position and for collision detection.
        # You can pass the center position as an argument.
        self.rect = self.image.get_rect(center=(self.pos_x, self.pos_y))
        self.dx = 2
        self.dy = 1

    def update(self):
        self.pos_x += self.dx
        self.pos_y += self.dy
        self.rect.center = (self.pos_x, self.pos_y)

我建议使用 vectors,因为它们更加通用和简洁.

I recommend using vectors, since they are more versatile and concise.

from pygame.math import Vector2

class Enemy(pygame.sprite.Sprite):

    def __init__(self, pos):
        # ...
        self.pos = Vector2(pos)
        self.velocity = Vector2(2, 1)

    def update(self):
        self.pos += self.velocity
        self.rect.center = self.pos

这篇关于Pygame:让事情比 1 慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆