Pygame移动图像

时间:2017-12-13 18:49:52

标签: python pygame

我刚刚开始使用pygame,我打算制作一个平台游戏,但到目前为止我无法获得我移动的精灵?

屏幕的代码位于已导入此屏幕的不同文件中

class Field
{
private:
    size_t* square = new size_t[5];
public:
    void del()
    {
        delete[] square;
    }
    void operator delete (void* p)
    {
        delete[] reinterpret_cast<Field*>(p)->square;
    }
};
int main()
{
    Field f;

    delete &f; 
    //or
    f.del();
}

当这个代码被播放时,它会显示一条白线,它执行的运动不是我创建的实际圆圈,我怎么能让圆圈移动?

2 个答案:

答案 0 :(得分:1)

draw.circle()只在屏幕上绘制一次并返回Rect() - 仅保持位置和大小的对象。当您更改sprite.xsprite.y时,它不会创建会移动的对象。

while循环之前,您可以创建Rect()以保持位置

 sprite = pygame.Rect(500, 250, 0, 0)

您可以像以前一样更改sprite.xsprite.y

while圈内,你必须draw.circle()使用sprite.xy

    DS.fill(WHITE)

    pygame.draw.circle(DS, WHITE, sprite.topleft, 20, 10)

    pygame.display.flip()

BTW:最好将位置保持为Rect()的中心位置,并将大小设置为2 * radius - 这意味着2 * 20 - 因此您可以将其与colliderect()一起使用检查碰撞。

 sprite = pygame.Rect(0, 0, 2*20, 2*20)
 sprite.center = (500, 250)

然后您可以使用sprite.center绘制圆圈

    DS.fill(WHITE)

    pygame.draw.circle(DS, WHITE, sprite.center, 20, 10)

    pygame.display.flip()

PyGame doc:Rect

答案 1 :(得分:0)

您是否想要创建Sprite类的实例然后移动它?然后你必须稍微改变一下类并在主循环中更新和blit精灵。

import pygame

pygame.init()
DS = pygame.display.set_mode((640, 480))
Vec = pygame.math.Vector2

WHITE = (255, 255, 255)
BLACK = (0,0,0,0)
clock = pygame.time.Clock()
FPS = 40

# Create a surface/image and draw a circle onto it.
sprite_image = pygame.Surface((50, 50))
pygame.draw.circle(sprite_image, WHITE, [25, 25], 20)


class Sprite(object):
    def __init__(self, pos):
        # Assign the global image to `self.image`.
        self.image = sprite_image
        # Create a rect which will be used as blit
        # position and for the collision detection.
        self.rect = self.image.get_rect()
        # Set the rect's center to the passed `pos`.
        self.rect.center = pos
        self._vx = 0
        self._vy = 0
        # Assign the pos also to these attributes.
        self._spritex = pos[0]
        self._spritey = pos[1]

    def update(self):
        self._vx = 0
        key = pygame.key.get_pressed()

        if key[pygame.K_RIGHT]:
            self._vx = 5
        if key[pygame.K_LEFT]:
            self._vx = -5

        # Adjust the position.
        self._spritex += self._vx
        self._spritey += self._vy
        # And update the center of the rect.
        self.rect.center = (self._spritex, self._spritey)


# Create an instance of the Sprite class.
sprite = Sprite([200, 250])

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Call the `update` method of the sprite to move it.
    sprite.update()

    DS.fill(BLACK)
    # Blit the sprite's image at the sprite's rect.topleft position.
    DS.blit(sprite.image, sprite.rect)

    pygame.display.flip()

    clock.tick(FPS)

pygame.quit()