我如何才能使敌人的子弹攻击更好?

时间:2020-06-13 19:48:34

标签: python pygame

所以最近我在帮助子弹攻击玩家方面有所帮助,但是它只是击中了玩家的y轴,就像我的玩家跳过子弹不会攻击一样,它只能随y轴移动

VIDEO就像我在中间一样,根本不会攻击玩家,只会攻击y轴

我的观点是,即使玩家跳跃,我如何才能使其在玩家所走的任何方向上变得更加流畅

这是子弹从敌人的枪支中射出并攻击靠近他的玩家的子弹,但不会被攻击

            for shootss in shootsright:

                if shootss.x < 500 and shootss.x > 0:

                    if enemyshoots1.x < playerman.x:

                        shootss.x +=  5
                    else:
                        shootss.x -= 5
                else:
                    shootsright.pop(shootsright.index(shootss))
                if shootss.y < 500 and shootss.y >0:
                    if enemyshoots1.y < playerman.y:
                        shootss.y += 5
                    else:
                        shootss.y -= 5
                else:
                    shootsright.pop(shootsright.index(shootss))

            if len(shootsright) < 1:
                    shootsright.append(Bools(round(enemyshoots1.x+enemyshoots1.width-107),round(enemyshoots1.y + enemyshoots1.height-50),(0,0,0)))
                # projectile class for each of the bullets


1 个答案:

答案 0 :(得分:2)

很难解码您要尝试执行的操作或编写的内容,这不是所有人都可以自行运行的最少代码,我花了两个视频甚至弄清您的“子弹”是心形曲折。

话虽这么说

我认为您是在要求子弹直接朝向玩家(弯曲),而不是在斜率1的直线(例如X的腿)上曲折移动。

猜测变量和上下文时,您似乎有一些错误,尤其是:

  • 在确定射手的走位时,您会查看射手的位置(而不是子弹头)。
  • 如果项目符号偏离0,0或500,500个角,您可能会使程序崩溃

要使子弹向玩家弯曲,您需要使用一些基本的三角弹,而不是+/- 5像素。对于您当前的实现,相应的项目符号速度为5 sqrt(2),因此,请保持该速度。您想弄清楚与播放器的总距离和方向,并按速度将总距离缩小,例如:

# Speed same as a vector of (5, 5)
speed = 5 * sqrt(2)

# Initial coordinates
px, py, bx, by = player_x, player_y, bullet_x, bullet_y

# Delta vector from bullet to player
dx, dy = px - bx, py - by

# Scaled vector (desired direction of bullet)
distance = sqrt(dx ** 2 + dy ** 2) or 1  # Shouldn't be 0
sx, sy = float(dx) / distance, float(dy) / distance

# Find new bullet coordinates
new_bx, new_by = bx + sx, by + sy

如果您需要使用整数坐标,则可能需要四舍五入,但这看起来可能很奇怪。

以下功能可帮助您简化逻辑:

from math import sqrt

# Speed same as a vector of (5, 5)
BULLET_SPEED = 5 * sqrt(2)


def move_bullet(bullet, player):
    '''
    Assumes bullet and player have .x and .y attributes
    and bullet.x/y can be modified
    '''
    # Delta vector from bullet to player
    dx = player.x - bullet.x
    dy = player.y - bullet.x

    # Unit vector (desired direction of bullet)
    # 'or 1' is to avoid division by 0 in case collision fails
    distance = sqrt(dx ** 2 + dy ** 2) or 1
    ux, uy = float(dx) / distance, float(dy) / distance

    # Move up to speed (don't go past player)
    length = min(BULLET_SPEED, distance)

    # Find new bullet coordinates
    bullet.x += length * ux
    bullet.y += length * uy

然后您可以在上面以

的形式调用它
if not (0 <= shootss.x <= 500 and 0 <= shootss.y <= 500):
    <pop bullet logic>
    continue
move_bullet(shootss, playerman)