python - 如何在pygame中使物体移动一定角度

标签 python pygame

我想将我的敌人从 start_x、start_y 变量移动到 pygame 中的假想三角形斜边到 target_x、target_y,我该怎么做? 这是我的实用程序文件的一部分

def polar_to_rectangularD(degrees, hypotenuse=1.0, inverted_y=True):
    opp = math.sin(math.degrees(degrees))*hypotenuse
    adj = math.cos(math.degrees(degrees))*hypotenuse
    if inverted_y:
        opp = -opp
    return opp,adj

def angle_towardsD(start_x, start_y, target_x, target_y, inverted_y=True):
    opp = target_y - start_y
    adj = target_x - start_x
    if inverted_y:
        opp = -opp
    angle = math.atan2(opp, adj)
    return math.degrees(angle)

这是我在主要内容中尝试用它做的一部分

if wall_spawn == 1:               
    enemy_y = player_ymax + player_half_height + enemy_radius     
    enemy_direction = -1
    spawn_angle = utility.angle_towardsD((win_width/6),650,(win_width/2),-100)
    enemy_x_offset, enemy_y_offset = utility.polar_to_rectangularD(spawn_angle,1)
    enemy_y -= enemy_y_offset
    enemy_movement += enemy_x_offset
#enemy_movement is set to None

最佳答案

您不需要计算角度。只需计算从敌人到玩家的向量即可。根据敌人的速度缩放矢量并将其添加到敌人的位置:

def move_enemy(start_x, start_y, target_x, target_y, spped):
    dx = target_x - start_x
    dy = target_y - start_y
    dist = math.hypot(dx, dy)
    if dist > 0:
        start_x += min(spped, dist) * dx / dist
        start_y += min(spped, dist) * dy / dist
    return start_x, start_y

最小示例:

import pygame, math

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
player_x, player_y, player_vel = 100, 100, 5
enemy_x, enemy_y, enemy_vel = 300, 300, 3

def move_enemy(start_x, start_y, target_x, target_y, speed):
    dx = target_x - start_x
    dy = target_y - start_y
    dist = math.hypot(dx, dy)
    if dist > 0:
        start_x += min(speed, dist) * dx / dist
        start_y += min(speed, dist) * dy / dist
    return start_x, start_y


run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False          
        
    keys = pygame.key.get_pressed()
    player_x = max(10, min(390, player_x + player_vel * (keys[pygame.K_d] - keys[pygame.K_a])))
    player_y = max(10, min(390, player_y + player_vel * (keys[pygame.K_s] - keys[pygame.K_w])))

    enemy_x, enemy_y = move_enemy(enemy_x, enemy_y, player_x, player_y, enemy_vel)

    window.fill(0)
    pygame.draw.circle(window, (0, 128, 255), (player_x, player_y), 10)
    pygame.draw.circle(window, (255, 32, 32), (enemy_x, enemy_y), 10)
    pygame.display.flip()

pygame.quit()
exit()

关于python - 如何在pygame中使物体移动一定角度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69776345/

相关文章:

python - 如何将多项式拟合到带有误差线的数据

python - 如何阻止我的蛇向自身移动(python,pygame)

python - Pygame.movi​​e 丢失

python - Python 中迭代两个键

python - 使用 PIL 在 python 中调整图像大小

python - 在 Google App Engine 中使用子过滤器/查询

python - Pygame 函数在 CollideRect 上不会返回 True

python - 我无法让 'player' 在 pygame 中双向移动,我该怎么做?

python - 调整闹钟时间以匹配python中的时钟时间

python - 将 tensorflow 图实现到 Keras 模型中