Python 为什么我的射弹的角度这么笨重?
我再次询问社区。我已经在这上面花了好几个小时了。我做了无数的谷歌搜索和视频。请版主们,不要关闭这个问题,因为有类似问题的帖子没有帮助Python 为什么我的射弹的角度这么笨重?,python,pygame,angle,Python,Pygame,Angle,我再次询问社区。我已经在这上面花了好几个小时了。我做了无数的谷歌搜索和视频。请版主们,不要关闭这个问题,因为有类似问题的帖子没有帮助 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,
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的部分。我以前做过这个,它不知怎么起作用了,但真的很奇怪。通过谷歌搜索和我自己的项目,我现在得到了很多不同的答案,所以我真的需要有人来解释什么是真正正确的方法。可以只存储积分坐标:
Rect对象的坐标都是整数
在下面的代码中
self.rect.x+=self.xv
self.rect.y+=self.yv
self.xv
和self.yv
的分数分量丢失,因为self.rect.x
和self.rect.y
只能存储整数值
您必须以浮点精度进行计算。添加一个x
和y
类的属性。增加更新中的属性,并同步rect
属性:
类箭头(pygame.sprite.sprite):
定义初始化(自):
# [...]
self.xv=数学cos(自角度)*自速度
self.yv=数学sin(自角度)*自速度
self.x=基本位置[0]
self.y=基准位置[1]
def更新(自我):
self.x+=self.xv
self.y+=self.yv
self.rect.center=圆形(self.x)、圆形(self.y)
所以数学是正确的,对吗?这主要是我想确认的。是的,角度的计算是正确的。问题是self.rect.x+=self.xv
和self.rect.y+=self.yv
@rabbi76:主持人也可以回答,我们大多数人都可以;-)