Python / Pygame:2d角动量/惯性

时间:2018-06-03 22:21:50

标签: python python-3.x vector pygame

我的第一个Python程序遇到了障碍,我认为我不具备解决问题​​的知识。

它是2d表面上的可控太空船,我想增加动量/惯性 我有它所以当发动机停止时,船继续沿着它前面的矢量行驶。 但是我只能让它“快速”捕捉到它旋转的新矢量。

我想要发生的是惯性矢量与新的指向矢量缓慢对齐,因为它加速 - 如旋转加速度? (我对数学不太热) - 我可以旋转惯性矢量,但是我需要以某种方式将它与新的指向矢量进行比较,并根据它们的差异对其进行修改?

如果有人可以建议我如何开始接近这个,那就太棒了 - 我怀疑我是从完全错误的方式来到这里的。 下面是一些代码(请温柔!)

使用的精灵是: - ship.png

import pygame
import sys
from math import sin, cos, pi, atan2
from pygame.locals import *
import random
from random import randint
from pygame.math import Vector2
import operator

"""solar system generator"""
"""set screen size and center and some global namespace colors for ease of use"""
globalalpha = 255
screenx = int(1200)
screeny = int(700)
centerx = int(screenx / 2)
centery = int(screeny / 2)
center = (centerx, centery)
black = (  0,   0,   0)
white = (255, 255, 255)
red = (209,   2,  22)
TRANSPARENT = (255,0,255)
numstars = 150
DISPLAYSURF = pygame.display.set_mode((screenx, screeny), 0, 32)
clock = pygame.time.Clock()
globaltimefactor = 1
shipimage = pygame.image.load('ship.png').convert()
DISPLAYSURF.fill(black)
screen_rect = DISPLAYSURF.get_rect()


class Playership(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.imageorig = pygame.image.load('ship.png').convert_alpha()
        self.startpos = (screen_rect.center)
        self.image = self.imageorig.copy()
        self.rect = self.imageorig.get_rect(center=self.startpos)
        self.angle = 0
        self.currentposx = 600
        self.currentposy = 350
        self.tuplepos = (self.currentposx, self.currentposy)
        self.speed = 1
        self.rotatespeed = 1.5
        self.initialvec = (600, 0)
        self.destination = 0
        self.anglechange = 0
        self.currentspeed = 0
        self.maxspeed = 5
        self.engineon = False
        self.newvec = (600, 0)
        self.newdestination = 0
        self.acceleration = 0.015
        self.inertiaspeed = 0
        self.transitionalvec = self.initialvec

    def get_angleafterstopping(self):
        newvec = self.initialvec
        self.newvec = newvec

    def get_destinationafterstopping(self):
        x_dist = self.newvec[0] - self.tuplepos[0]
        y_dist = self.newvec[1] - self.tuplepos[1]
        self.newdestination = atan2(-y_dist, x_dist) % (2 * pi)

    def get_destination(self):
        x_dist = self.initialvec[0] - self.tuplepos[0]
        y_dist = self.initialvec[1] - self.tuplepos[1]
        self.destination = atan2(-y_dist, x_dist) % (2 * pi)

    def moveship(self):
        if self.engineon is True:
            self.currentspeed = self.currentspeed + self.acceleration
            if self.currentspeed > self.maxspeed:
                self.currentspeed = self.maxspeed
            elif self.currentspeed < 0:
                self.currentspeed = 0
            self.inertiaspeed = self.currentspeed
        elif self.engineon is False:
            self.currentposx = self.currentposx + (cos(self.newdestination) * self.inertiaspeed * globaltimefactor)
            self.currentposy = self.currentposy - (sin(self.newdestination) * self.inertiaspeed * globaltimefactor)
            self.tuplepos = (self.currentposx, self.currentposy)
            self.rect.center = self.tuplepos
            return
        self.get_destination()
        self.currentposx = self.currentposx + (cos(self.destination) * self.currentspeed * globaltimefactor)
        self.currentposy = self.currentposy - (sin(self.destination) * self.currentspeed * globaltimefactor)
        self.tuplepos = (self.currentposx, self.currentposy)
        self.rect.center = self.tuplepos

    def rotateship(self, rotation):
        self.anglechange = self.anglechange - (rotation * self.rotatespeed * globaltimefactor)
        self.angle += (rotation * self.rotatespeed * globaltimefactor)
        self.image = pygame.transform.rotate(self.imageorig, self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)
        initialvec = self.tuplepos + Vector2(0, -600).rotate(self.anglechange * globaltimefactor)
        initialvec = int(initialvec.x), int(initialvec.y)
        self.initialvec = initialvec




myship = Playership()
all_sprites_list = pygame.sprite.Group()
all_sprites_list.add(myship)
firsttimedone = False


def main():

    done = False
    while not done:
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_LEFT]:
            myship.rotateship(1)
        if keys_pressed[pygame.K_RIGHT]:
            myship.rotateship(-1)
        if keys_pressed[pygame.K_UP]:
            myship.engineon = True
            myship.moveship()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit();
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                    myship.engineon = False
                    myship.currentspeed = 0
                    myship.get_angleafterstopping()
                    myship.get_destinationafterstopping()
        DISPLAYSURF.fill(black)
        all_sprites_list.update()
        all_sprites_list.draw(DISPLAYSURF)
        pygame.draw.line(DISPLAYSURF, white, (myship.tuplepos), (myship.initialvec))
        pygame.draw.line(DISPLAYSURF, red, (myship.tuplepos), (myship.newvec))
        pygame.display.flip()
        if myship.engineon is False:
            myship.moveship()
        clock.tick(50)
        pygame.display.set_caption("fps: " + str(clock.get_fps()))


if __name__ == '__main__':
    pygame.init()
    main()
    pygame.quit(); sys.exit();

编辑:

我修复了它:只需要更好地理解矢量 船开始时加速度和速度都表示为矢量。

self.position = vec(screenx / 2, screeny / 2)
self.vel = vec(0, 0)
self.acceleration = vec(0, -0.2)  # The acceleration vec points upwards from the starting ship position

旋转船将该矢量旋转到位

self.acceleration.rotate_ip(self.angle_speed)
self.angle += self.angle_speed
self.image = pygame.transform.rotate(self.imageorig, -self.angle)
self.rect = self.image.get_rect(center=self.rect.center)

正在加速:

self.vel += self.acceleration * self.enginepower * globaltimefactor

更新职位:

self.position += self.vel
self.rect.center = self.position

我使它变得比它需要的更难,速度需要保持不变,直到被旋转的加速度矢量作用。我不知道如何将矢量添加到一起等。

1 个答案:

答案 0 :(得分:1)

我修复了它:只需要更好地理解矢量 船开始时加速度和速度都表示为矢量。

self.position = vec(screenx / 2, screeny / 2)
self.vel = vec(0, 0)
self.acceleration = vec(0, -0.2)  # The acceleration vec points upwards from the starting ship position

旋转船将该矢量旋转到位

self.acceleration.rotate_ip(self.angle_speed)
self.angle += self.angle_speed
self.image = pygame.transform.rotate(self.imageorig, -self.angle)
self.rect = self.image.get_rect(center=self.rect.center)

正在加速:

self.vel += self.acceleration * self.enginepower * globaltimefactor

更新职位:

self.position += self.vel
self.rect.center = self.position

我使它变得比它需要的更难,速度需要保持不变,直到被旋转的加速度矢量作用。我不知道如何将矢量添加到一起等。