[英]Pygame move a object to mouse
我想通过以下方式计算图像的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)
我该如何解决?
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.