繁体   English   中英

Pygame-旋转和移动宇宙飞船(多边形)

[英]Pygame - Rotate and move a spaceship (Polygon)

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

我想做一个经典风格的小行星游戏,我从飞船开始。

我所做的就是画出一些形状像飞船的线条:

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)

船看起来像这样:

在此处输入图片说明

现在要知道的重要事项:

元组(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

在此处输入图片说明

问题是:如何使它沿着宇宙飞船指向的方向前进或后退?

要么

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

处理运动和旋转的最简单,最通用的方法是使用一些矢量数学(也可以应用于3D图形)。 您可以保留一个二维矢量,表示您的船的前进方向。 例如,如果您的船开始朝上,而(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小类,该类可以执行一些基本操作,例如,点,叉,多重,加,乘,归一化等。

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

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

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

暂无
暂无

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

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