首页 > 解决方案 > 为什么我的弹丸的角度如此笨拙?

问题描述

我再次向社区提问。我已经在这上面花了几个小时。我做了无休止的谷歌搜索和视频。请版主,不要关闭这个问题,因为类似问题的帖子没有帮助。

import pygame
import math
pygame.init()
win_height=400
win_width=800
win=pygame.display.set_mode((0,0),pygame.FULLSCREEN)
pygame.display.set_caption("game")

white=(255,255,255)
black=(0,0,0)
blue=(0,0,255)
green=(255,169,69)
red=(255,0,0)

base_pos=(20,680)

clock=pygame.time.Clock()
arrows=pygame.sprite.Group()

class Arrow(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image=pygame.Surface((5,5))
        self.image.fill(white)
        self.rect=self.image.get_rect()
        self.rect.center=base_pos
        self.speed=2
        self.angle=math.atan2(mouse_pos[1]-base_pos[1],mouse_pos[0]-base_pos[0])

        #I did learn the formula for finding the angle between two points in radians here, but I can't 
        move it properly

        self.xv=math.cos(self.angle)*self.speed
        self.yv=math.sin(self.angle)*self.speed
    def update(self):
        self.rect.x+=self.xv
        self.rect.y+=self.yv

timer=0
while True:
    timer+=0.017
    pygame.event.get()
    mouse_pos=pygame.mouse.get_pos()
    mouse_down=pygame.mouse.get_pressed()
    keys=pygame.key.get_pressed()
    clock.tick(60)

    if keys[pygame.K_ESCAPE]:
        pygame.quit()

    win.fill(blue)
    pygame.draw.rect(win,green,(0,700,2000,2000))
    pygame.draw.rect(win,red,(20,680,20,20))
    if timer>0.5:
        arrow=Arrow()
        arrows.add(arrow)
    arrows.update()
    arrows.draw(win)
    pygame.display.update()

我怀疑罪魁祸首是我计算 xv 和 yv 的部分。我以前这样做过,它以某种方式起作用,但这真的很奇怪。我现在通过谷歌搜索和我自己的项目得到了很多不同的答案,所以我真的需要有人来解释真正正确的方法是什么。

标签: pythonpygameangle

解决方案


pygame.Rect可以只存储积分坐标:

Rect 对象的坐标都是整数。

在下面的代码中

self.rect.x += self.xv
self.rect.y += self.yv

self.xv和的小数部分self.yv丢失了,因为self.rect.x并且self.rect.y只能存储整数值。

您必须以浮点精度进行计算。给类添加一个xandy属性。在更新中增加属性并同步rect属性:

class Arrow(pygame.sprite.Sprite):
    def __init__(self):
        # [...]

        self.xv = math.cos(self.angle)*self.speed
        self.yv = math.sin(self.angle)*self.speed
        self.x = base_pos[0]
        self.y = base_pos[1]
   
     def update(self):
        self.x += self.xv
        self.y += self.yv
        self.rect.center = round(self.x), round(self.y)

推荐阅读