Python 为什么我的子弹与鼠标成90度角?
所以我在网上找到了一些答案,在尝试其中一个后,我发现“子弹”总是与光标成90度角。有办法解决这个问题吗?我在三角学方面的经验很少。另外,我对这件事很陌生,所以不要介意代码中缺少结构Python 为什么我的子弹与鼠标成90度角?,python,pygame,trigonometry,angle,bullet,Python,Pygame,Trigonometry,Angle,Bullet,所以我在网上找到了一些答案,在尝试其中一个后,我发现“子弹”总是与光标成90度角。有办法解决这个问题吗?我在三角学方面的经验很少。另外,我对这件事很陌生,所以不要介意代码中缺少结构 import pygame import math pygame.init() win_height=800 win_width=800 win=pygame.display.set_mode((win_width,win_height)) pygame.display.set_caption("Shoot
import pygame
import math
pygame.init()
win_height=800
win_width=800
win=pygame.display.set_mode((win_width,win_height))
pygame.display.set_caption("Shooter Game")
white=(255,255,255)
black=(0,0,0)
clock=pygame.time.Clock()
bullets=pygame.sprite.Group()
class soldier_class(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.image.load("inkscape images for games/soldier2.png")
self.image=pygame.transform.scale(self.image,(100,150))
self.rect=self.image.get_rect()
def update(self):
new_rect=soldier_rotated.get_rect(center=(soldier.rect.x,soldier.rect.y))
win.blit(soldier_rotated,(new_rect.x,new_rect.y))
class bullet_class(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface((25,25))
self.image.fill(black)
self.rect=self.image.get_rect()
self.angle=0
def update(self):
self.rect.x+=5*math.cos(self.angle)
self.rect.y-=5*math.sin(self.angle)
soldier=soldier_class()
soldier.rect.x=200
soldier.rect.y=200
while True:
mouse=pygame.mouse.get_pos()
clock.tick(60)
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
key=pygame.key.get_pressed()
if key[pygame.K_w]:
soldier.rect.y-=5
if key[pygame.K_s]:
soldier.rect.y+=5
if key[pygame.K_d]:
soldier.rect.x+=5
if key[pygame.K_a]:
soldier.rect.x-=5
if key[pygame.K_SPACE]:
bullet=bullet_class()
bullet.rect.x=soldier.rect.x
bullet.rect.y=soldier.rect.y
bullet.angle=math.atan2(mouse[0]-bullet.rect.x,mouse[1]-bullet.rect.y)
bullets.add(bullet)
angle=math.atan2(mouse[0]-soldier.rect.x,mouse[1]-soldier.rect.y)/6.28*360
soldier_rotated=pygame.transform.rotate(soldier.image,angle)
win.fill(white)
soldier.update()
bullets.update()
bullets.draw(win)
pygame.display.update()
因为角度的计算是错误的:
为True时:
# [...]
如果键[pygame.K_SPACE]:
# [...]
#bullet.angle=math.atan2(鼠标[0]-bullet.rect.x,鼠标[1]-bullet.rect.y)
bullet.angle=math.atan2(soldier.rect.y-鼠标[1],鼠标[0]-soldier.rect.x)
#角度=math.atan2(鼠标[0]-soldier.rect.x,鼠标[1]-soldier.rect.y)/6.28*360
角度=math.atan2(soldier.rect.y-鼠标[1],鼠标[0]-soldier.rect.x)*180/math.pi
见并且可以通过
atan2(y,x)
(而不是atan2(x,y)
)计算角度。通过交换sin
和cos
来补偿此错误,用另一个错误补偿一个错误。