簡體   English   中英

pygame將對象移動到鼠標

[英]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)

我該如何解決?

一個清楚地說明它的例子

您的計算有三件事是錯誤的。

  1. math.atan2以y和x的順序接受參數,而不是x和y的順序。 這不是什么大問題,因為您可以彌補。
  2. math.cosmath.sin弧度作為參數。 您已將角度轉換為
  3. 余弦表示x值,而正弦表示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)

使用解決方案的簡短示例

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM