簡體   English   中英

在pygame中使用move_ip移動多邊形

[英]Move polygon with move_ip in pygame

我無法使用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()

謝謝

問題是您的Rect與您繪制的多邊形毫無關系。 您每次都只需將其繪制在相同位置即可。

最好一次創建一個Surface一次在該Surface上繪制多邊形,然后在繪制新Surface時使用spaceship作為位置。

我建議從Sprite子類化,在__init__函數中創建該Surface ,然后將Rect保存在self.rect而不是在spaceship變量中。

然后使用Spritedraw函數或將Sprite放入Group

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM