【问题标题】:Move polygon with move_ip in pygame在pygame中使用move_ip移动多边形
【发布时间】:2015-07-18 12:00:55
【问题描述】:

我无法在 pygame 中使用函数 move_ip() 来移动多边形,如果我绘制一个矩形,代码效果很好,但不能使用多边形。按任意方向键都没反应。

我想我不需要宇宙飞船矩形,因为多边形是 pygame 的矩形,但它似乎不对,我不知道,我搞砸了。

这是我的 pygame 代码:

import sys, os
import pygame
from pygame.locals import *
import numpy as np

if sys.platform in ["win32","win64"]: os.environ["SDL_VIDEO_CENTERED"]='1'

width_screen = 600
height_screen = 480
screen_size = (width_screen, height_screen)
positionx_screen = 0
positiony_screen = 32
title_window = 'ASTEROIDS'

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

spaceship = pygame.Rect(200, 475, 120, 20)

def quit_screen(event):
    if event.type == QUIT:
        pygame.quit()
        sys.exit()


class Spaceship():
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.colour = WHITE
        self.thickness = 0
        self.movex = 20

    def draw_nave(self):
        vertices = np.array([[screen_size[0]/2, screen_size[1] /2 - 30],[screen_size[0]/2 + 15, screen_size[1]/2],
                             [screen_size[0]/2-15, screen_size[1] / 2]])
        pygame.draw.polygon(screen_game, self.colour, vertices, self.thickness)


    def move_spaceship_right(self):
        spaceship.move_ip(self.movex, 0)


    def move_spaceship_left(self):
        spaceship.move_ip(- self.movex, 0)


def game():
    pygame.init()
    running = True
    global screen_game
    screen_game = pygame.display.set_mode(screen_size,
                                          positionx_screen, positiony_screen)
    pygame.display.set_caption(title_window)

    clock = pygame.time.Clock()

    my_spaceship = Spaceship(200, 475, 120, 20)

    screen_game.fill(BLACK)
    while running:
        screen_game.fill(BLACK)
        for event in pygame.event.get():
            quit_screen(event)
            if event.type == pygame.KEYDOWN:
                if event.key == K_RIGHT:
                    my_spaceship.move_spaceship_right()
                if event.key == K_LEFT:
                    my_spaceship.move_spaceship_left()


        my_spaceship.draw_nave()
        pygame.display.flip()
        clock.tick(60)

if __name__ == "__main__":
    try:
        game()
    except:
        pygame.quit()

谢谢

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    问题是您的Rect 与您绘制的多边形没有任何关系。您只需每次都在相同的位置绘制它。

    最好创建一次Surface,在该Surface 上绘制一次多边形,并在绘制新的Surface 时使用spaceship 作为位置。

    我建议从Sprite 子类化,在__init__ 函数中创建Surface,并将Rect 保存在self.rect 中而不是spaceship 变量中。

    然后要么使用Spritedraw 函数,要么将你的Sprite 放入Group

    【讨论】:

    • 对不起,我不明白你的意思。我不明白为什么我没有图像时必须使用 Sprites。谢谢
    猜你喜欢
    • 2022-12-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2014-12-02
    相关资源
    最近更新 更多