Pygame - 旋转并移动宇宙飞船(Polygon)

时间:2016-12-15 03:13:42

标签: python pygame

好的,我一整天都在工作,但我还没有找到逻辑。

我想制作经典风格的小行星游戏,我是从宇宙飞船开始的。

我所做的是绘制一些太空船形状的线条:

import pygame
import colors
from  helpers import *

class Ship :
    def __init__(self, display, x, y) :
        self.x = x
        self.y = y
        self.width = 24
        self.height = 32
        self.color = colors.green
        self.rotation = 0
        self.points = [
            #A TOP POINT
            (self.x, self.y - (self.height / 2)),
            #B BOTTOM LEFT POINT
            (self.x - (self.width / 2), self.y + (self.height /2)),
            #C CENTER POINT
            (self.x, self.y + (self.height / 4)),
            #D BOTTOM RIGHT POINT
            (self.x + (self.width / 2), self.y + (self.height / 2)),
            #A TOP AGAIN
            (self.x, self.y - (self.height / 2)),
            #C A NICE LINE IN THE MIDDLE
            (self.x, self.y + (self.height / 4)),
        ]

    def move(self, strdir) :
        dir = 0
        if strdir == 'left' :
            dir = -3
        elif strdir == 'right' :
            dir = 3

        self.points = rotate_polygon((self.x, self.y), self.points, dir)

    def draw(self, display) :
        stroke = 2
        pygame.draw.lines(display, self.color, False, self.points, stroke)

这艘船看起来像这样:

enter image description here

现在要了解的重要事项:

元组(self.x,self.y)是宇宙飞船的中间部分。

使用此功能,我设法使用键A和D

按顺序旋转(旋转)它
def rotate_polygon(origin, points, angle) :
    angle = math.radians(angle)
    rotated_polygon = []

    for point in points :
        temp_point = point[0] - origin[0] , point[1] - origin[1]
        temp_point = (temp_point[0] * math.cos(angle) - temp_point[1] * math.sin(angle), 
                      temp_point[0] * math.sin(angle) + temp_point[1] * math.cos(angle))
        temp_point = temp_point[0] + origin[0], temp_point[1] + origin[1]
        rotated_polygon.append(temp_point)

    return rotated_polygon

enter image description here

问题是:如何让它向太空船指向的方向前进或后退?

如何更新self.x和self.y值并在self.points列表中更新它们并保留旋转?

2 个答案:

答案 0 :(得分:2)

处理移动和旋转的最简单,最通用的方法是使用一些矢量数学(也可以应用于3D图形)。您可以保留一个2D矢量来表示您的船的前进方向。例如,如果您的船开始朝上,而您的(0,0)坐标是左上角。你可以做到。

self.forward = Vector2D(0, -1)  # Vector2D(x, y)

旋转时,必须旋转此矢量。您可以使用以下内容进行旋转。

self.forward.x = self.forward.x * cos(angle) - self.forward.y * sin(angle)
self.forward.y = self.forward.x * sin(angle) + self.forward.y * cos(angle)

然后,当您想要移动船只时,您可以相对于此向量转换船舶点数。例如。

self.x += forward.x * velocity.x
self.y += forward.y * velocity.y

我强烈建议您编写一个可以执行某些基本操作的Vector2D类,例如: dot,cross,mult,add,sub,normalize等。

如果您熟悉矩阵,那么如果使用矩阵而不是线性方程组来实现这些操作会变得更容易。

答案 1 :(得分:0)

在我看来,您应该能够简单地执行以下操作。

def updatePosition(self, dx, dy):
    self.x += dx
    self.y += dy

    newPoints = []
    for (x,y) in self.points:
       newPoints.append((x+dx, y+dy))

    self.points = newPoints
相关问题