繁体   English   中英

如何在Pygame中移动非矩形对象?

[英]How to move non-rectangular objects in Pygame?

在我的游戏, 战舰 ,我想当按下方向键来移动船。 我的船包括一个五边形多边形和五条边界线。 我已经在网上搜寻了移动它的方法,但我只是想方设法让矩形和方形船移动。 以下是我的代码(没有任何移动船的尝试):

import pygame,sys
from pygame.locals import *

pygame.init()

black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
yellow = (255,242,0)
ship_body = (33, 117, 243)

screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("Battle Ship")
background = pygame.image.load("Sky Background.png")

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()        


    screen.blit(background, (0,0))
    ship = [
            pygame.draw.polygon(screen, ship_body,((100,50),(180,95),(320,95),(400,50),(250,35))),
            pygame.draw.line(screen, black, (100,50),(180,95),1),
            pygame.draw.line(screen, black, (180,95),(320,95),1),
            pygame.draw.line(screen, black, (320,95),(400,50),1),
            pygame.draw.line(screen, black, (400,50),(250,35),1),
            pygame.draw.line(screen, black, (250,35),(100,50),1),
            ]

    pygame.display.update()        

您可以为多边形制作一个点列表,并递增和递减它们:

import pygame,sys
from pygame.locals import *

pygame.init()

black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
yellow = (255,242,0)
ship_body = (33, 117, 243)

screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("Battle Ship")
#background = pygame.image.load("Sky Background.png")

pygame.key.set_repeat(50,50)

ship_points = [ [100, 50], [180, 95], [320, 95], [400, 50], [250,35] ] 
x = 0
y = 0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()        

        if event.type == pygame.KEYDOWN:
           if event.key == pygame.K_LEFT: 
               x = -1

           if event.key == pygame.K_RIGHT: 
               x = 1

           if event.key == pygame.K_UP: 
               y = -1

           if event.key == pygame.K_DOWN: 
               y = 1

           for point in ship_points:
                point[0] += x
                point[1] += y

           x=0
           y=0

  #  screen.blit(background, (0,0))
    screen.fill(black)
    pygame.draw.polygon(screen, ship_body, ship_points)
    '''
    ship = [
            pygame.draw.polygon(screen, ship_body,((100,50),(180,95),(320,95),(400,50),(250,35))),
            pygame.draw.line(screen, black, (100,50),(180,95),1),
            pygame.draw.line(screen, black, (180,95),(320,95),1),
            pygame.draw.line(screen, black, (320,95),(400,50),1),
            pygame.draw.line(screen, black, (400,50),(250,35),1),
            pygame.draw.line(screen, black, (250,35),(100,50),1),
            ]
    '''
    pygame.display.update() 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM