我想通过计算图像的x和y来慢慢将精灵(子弹)移动到鼠标坐标:
angle = math.atan2(dX,dY) * 180/math.pi
x = speed * sin(angle)
y = speed * cos(angle)
问题是即使精灵指向鼠标(在这个游戏中,枪中)具有相同的角度(使用pygame.transform.rotate),子弹仍会移动到不正确的坐标。
当前代码示例:
dX = MouseX - StartpointX
dY = Mouse_Y - StartPointY
Angle = ( math.atan2(dX,dY) * 180/math.pi ) + 180
Bullet_X =Bullet_X + Speed * math.sin(Angle)
Bullet_Y = Bullet_Y + Speed * math.cos(Angle)
我该如何解决这个问题?
答案 0 :(得分:0)
math.atan2
以y和x的顺序获取参数,而不是x和y。这不是一个大问题,因为你可以弥补它。math.cos
和math.sin
将弧度作为参数。您已将角度转换为度。所以计算应该是这样的:
dx = mouse_x - x
dy = mouse_y - y
angle = math.atan2(dy, dx)
bullet_x += speed * math.cos(angle)
bullet_y += speed * math.sin(angle)
import pygame
import math
pygame.init()
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
x, y, dx, dy = 360, 240, 0, 0
player = pygame.Surface((32, 32))
player.fill((255, 0, 255))
bullet_x, bullet_y = 360, 240
speed = 10
bullet = pygame.Surface((16, 16))
bullet.fill((0, 255, 255))
def update(mouse_x, mouse_y):
global x, y, dx, dy, bullet_x, bullet_y
dx = mouse_x - x
dy = mouse_y - y
angle = math.atan2(dy, dx)
bullet_x += speed * math.cos(angle)
bullet_y += speed * math.sin(angle)
run_update = False
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
run_update = True
mouse_x, moues_y = pygame.mouse.get_pos()
if run_update:
update(mouse_x, moues_y)
if 0 > bullet_x or bullet_x > 800 or 0 > bullet_y or bullet_y > 800:
bullet_x, bullet_y = 360, 240
run_update = False
screen.fill((0, 0, 0))
screen.blit(player, (x, y))
screen.blit(bullet, (bullet_x, bullet_y))
pygame.display.update()