【问题标题】:Python - Shoot a bullet in the direction (angle in degrees) my spaceship is facingPython - 向我的宇宙飞船所面对的方向(以度为单位)发射子弹
【发布时间】:2016-12-18 18:58:28
【问题描述】:

关于这个有很多问题。但是他们都没有具体解决我问题的答案,我整天都在尝试谷歌。

我的问题很简单。

我有这艘可以移动和旋转的太空船,我已经在跟踪它的航向,它所面对的方向。例如,在下图中,船的航向约为 45 度 它从 0°(从顶部开始顺时针方向)到 359°

我只需要让子弹沿着我的飞船所面对的方向(航向)直线前进,从我的飞船当前所在的X,Y坐标开始

Projectile 类:

class Projectile(object) :

    def __init__(self, x, y, vel, screen) :
        self.screen = screen
        self.speed = 1 #Slow at the moment while we test it
        self.pos = Vector2D(x, y)
        self.velocity = vel #vel constructor parameter is a Vector2D obj
        self.color = colors.green

    def update(self) :
        self.pos.add(self.velocity)

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

现在我的船级的射击方法:

class Ship(Polygon) :

    # ... A lot of ommited logic and constructor

    def shoot(self) :
        p_velocity = # .......... what we need to find
        p = Projectile(self.pos.x, self.pos.y, p_velocity, self.screen)
        # What next?

【问题讨论】:

  • 更新self.pos的逻辑在哪里?也许保留最后 2 个位置的列表并从中计算速度?
  • @jmunsch 我不认为我理解正确。这两个类都有一个 属性,它只是它们在屏幕上的位置。它们通过每帧添加速度值来更新
  • 你为 Vector2D 导入什么库?
  • Vector 2D 是我自己编写的自定义类。它只是用 X,Y 的东西进行操作。像加法,乘法,从角度获取向量(我用它来使宇宙飞船朝着所面对的方向前进)等。用于船的原理似乎不适用于子弹,这令人困惑。在这里查看gist.github.com/anonymous/fb226b641649905cf059fbbb4c0f123d
  • @jmunsch 这行不通,因为在这个小游戏中,宇宙飞船可以漂移,所以子弹不会像子弹一样,而是像你刚刚从窗户掉出来的东西

标签: python pygame


【解决方案1】:

考虑到船的角度,试试:

class Projectile(object) :
    def __init__(self, x, y, ship_angle, screen) :
        self.screen = screen
        self.speed = 5 #Slow at the moment while we test it
        self.pos = Vector2D(x,y)
        self.velocity = Vector2D().create_from_angle(ship_angle, self.speed, return_instance=True)
        self.color = colors.green

    def update(self) :
        self.pos.add(self.velocity)

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

Vector2D的相关部分:

def __init__(self, x = 0, y = 0) : # update to 0
    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
    print(x, y, self.x, self.y, angle)
    self.x += float(x)
    self.y += float(y)
    if return_instance :
        return self

【讨论】:

  • 会尝试向您展示我们这样做时它的行为方式
  • 这里发生的情况是子弹是在 0,0 坐标中创建的,而不是船所在的位置:s
  • 您要么将速度添加到位置,要么将位置替换为速度。那么(0,100)呢?为什么你仍然需要这个检查?你能像我是一只橡皮鸭一样向我解释吗?
  • @n.m.是的,这更有意义。 create_from_angle 可能有一个更好的名字。并且不需要检查。
  • @JuanBonnett 应该是一个单独的问题,并带有指向此页面的链接以供参考。
猜你喜欢
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多