Python - 让我的太空飞船朝着它面向第2部分的方向射击

时间:2016-12-19 00:53:34

标签: python vector pygame

编辑,解决问题的基础

在这个问题中,我在一些好人的帮助下做了一些改进:Python - Shoot a bullet in the direction (angle in degrees) my spaceship is facing

现在的问题是,虽然使太空船朝着这个方向加速的原则正面临着,但似乎并没有与射弹一起工作。当子弹以某些角度从船上射出时,似乎有一种奇怪的偏移。

enter image description here

我要把代码放在下面,方法UPDATE()和BOOST()是负责使船舶移动的工具。

弹丸使用几乎相同的原理,没有加速度。

这是一段视频,因此您可以直观地看到游戏正在运行并查看错误https://youtu.be/-s7LGuLhePI

这是我的Ship和vector类,它们与问题有关。 (我将省略并删除不必在此处显示的方法)

Class Ship包含ship元素和Projectile类

import pygame
import colors
import math
from vectors import Vector2D
from polygon import Polygon
from helpers import *

class Ship(Polygon) :

    def __init__(self, x, y, screen) :
        self.screen = screen
        self.pos = Vector2D(x, y)
        self.size = 18
        self.color = colors.green
        self.rotation = 0
        self.points = [
                        (-self.size, self.size),
                        (0, self.size / 3),
                        (self.size, self.size),
                        (0, -self.size)
                      ]
        self.translate((self.pos.x, self.pos.y))
        self.velocity = Vector2D(0, 0)
        self.projectiles = []

    def shoot(self) :
        p = Projectile(self.pos.x, self.pos.y, self.rotation, self.screen)
        self.projectiles.append(p)

    def turn(self, dir) :
        turn_rate = 4
        if dir == 'left' :
            deg = -turn_rate
        elif dir == 'right' :
            deg = turn_rate
        else :
            deg = 0

        self.rotate((self.pos.x, self.pos.y), deg)

        if self.rotation > 360 :
            self.rotation -= 360
        elif self.rotation < 0 :
            self.rotation += 360
        else :
            self.rotation += deg

        #print('HDG: ' + str(self.rotation))

    def boost(self) :
        #print(self.velocity.x, ',', self.velocity.y)
        force = Vector2D().create_from_angle(self.rotation, 0.1, True)

        #Limits the speed
        if (((self.velocity.x <= 4) and (self.velocity.x >= -4)) 
            or 
            ((self.velocity.y <= 4) and (self.velocity.y >= -4))) :
            self.velocity.add(force)

        #print('Velocity: ' + str(self.velocity.x) + ',' + str(self.velocity.y))

    def update(self) :
        #Adds friction
        f = 0.98
        self.velocity.mult((f, f))

        # Resets ship possition when it's out of the screen
        if self.pos.x > (self.screen.get_width() + self.size) :
            #print('COLLIDED RIGHT')
            self.pos.x -= self.screen.get_width() + self.size
            self.translate((-(self.screen.get_width() + self.size), 0))
        elif self.pos.x < -self.size :
            #print('COLLIDED LEFT')
            self.pos.x += self.screen.get_width() + self.size
            self.translate(((self.screen.get_width() + self.size), 0))
        if self.pos.y > (self.screen.get_height() + self.size) :
            #print('COLLIDED BOTTOM')
            self.pos.y -= self.screen.get_height() + self.size
            self.translate((0, -(self.screen.get_height() + self.size)))
        elif self.pos.y < -self.size :
            #print('COLLIDED TOP')
            self.pos.y += self.screen.get_height() + self.size
            self.translate((0, (self.screen.get_height() + self.size)))

        self.pos.x += self.velocity.x #TODO: simplify using V2D add function
        self.pos.y += self.velocity.y

        self.translate(self.velocity.tuple())

        #Update projectiles that have been shot
        for p in self.projectiles :
            p.update()

    def draw(self) :
        stroke = 3
        pygame.draw.polygon(self.screen, self.color, self.points, stroke)

        #Draws projectiles that have been shot
        for p in self.projectiles :
            p.draw()

class Projectile(object) :

    def __init__(self, x, y, ship_angle, screen) :
        self.screen = screen
        self.speed = 3 #Slow at the moment while we test it
        self.direction = ship_angle;
        self.pos = Vector2D(x, y)
        self.color = colors.green

    def update(self) :
        self.pos.add(Vector2D().create_from_angle(self.direction, self.speed, return_instance = True))

    def draw(self) :
        pygame.draw.circle(self.screen, self.color, self.pos.int().tuple(), 2, 0)

CLASS VECTOR(用于根据元素“标题”计算向量并应用速度)

import math

class Vector2D() :

    def __init__(self, x = None, y = None) :
        self.x = x
        self.y = y

    def create_from_angle(self, angle, magnitude, return_instance = False) :
        angle = math.radians(angle) - math.pi / 2
        x = math.cos(angle) * magnitude
        y = math.sin(angle) * magnitude
        self.x = x
        self.y = y

        if return_instance :
            return self

    def tuple(self) :
        return (self.x, self.y)

    def int(self) :
        self.x = int(self.x)
        self.y = int(self.y)
        return self

    def add(self, vector) :
        if isinstance(vector, self.__class__) : # vector is an instance of this class
            self.x += vector.x 
            self.y += vector.y
        else : # vector is a tuple
            self.x += vector[0]
            self.y += vector[1]

    def mult(self, vector) :
        if isinstance(vector, self.__class__) : # vector is an instance of this class
            self.x *= vector.x 
            self.y *= vector.y
        else : # vector is a tuple
            self.x *= vector[0]
            self.y *= vector[1]

基于标记答案的解决方案

Pygame.draw.circle()只接受INTEGER值元组作为位置参数,由于我们进行的计算,这是不可能的,因为角度计算的结果总是浮点数。

解决方案是将绘图方法改为在弹丸类中使用Ellipse而不是Circle:

class Projectile(object) :

    def __init__(self, x, y, ship_angle, screen) :
        self.screen = screen
        self.speed = 3 #Slow at the moment while we test it
        self.direction = ship_angle;
        self.velocity = Vector2D().create_from_angle(self.direction, self.speed, return_instance = True)
        self.pos = Vector2D(x, y)
        self.color = colors.green
        # Properties neccesary to draw the ellipse in the projectile position
        self.size = 4
        self.box = (0,0,0,0)

    def update(self) :
        self.pos.add(self.velocity)
        self.box = (self.pos.x, self.pos.y, self.size, self.size)

    def draw(self) :
        stroke = 2
        pygame.draw.ellipse(self.screen, self.color, self.box, stroke)

1 个答案:

答案 0 :(得分:3)

事实证明,错误在你的Vector2D课程中出人意料,但在你期望的函数中却没有!你的Vector2D().create_from_angle()函数很好并创建了正确的角度,假设up为0且角度值顺时针增加,即使它与0的“标准数学约定”相反,逆时针方向是增加角度值。

真正的问题位于Vector2D().int()函数中,该函数用作draw()类中Projectile函数的一部分。将float数字转换为int只会截断小数值,因此您可以使用int强制转换以及python的round函数,如下所示:

def int(self) :
    self.x = int(round(self.x))
    self.y = int(round(self.y))
    return self

然而,即使你做了这个修复,你会注意到由于与你的船尖相比更圆,角度仍然略微偏离。这是因为self.pos.int()函数下的Projectile.draw()覆盖当前位置,其中包含一个不准确的四舍五入的版本,并继续添加到{{1}中功能。最佳解决方案可能是避免使用Projectile.update()功能,并将Vector2D.int()函数替换为:

Projectile.draw()

上述修改将使您的射弹从您的船尖完美射击,但会导致抖动,因为位置有时会向上舍入,有时会在x或y坐标上向下舍入。使用修改后的def draw(self) : pos_x = int(round(self.pos.x)) pos_y = int(round(self.pos.y)) pygame.draw.circle(self.screen, self.color, (pos_x, pos_y), 2, 0) 功能导致非紧张但不准确的射弹射击。哪个错误最好取决于您。如果这很清楚,请告诉我!