0

I have a two points - start and destination. (X, Y) I must to create a bullet. I created a simply code:

def Entities():
    ##BULLETS
    #bullets array
    for x in gd.bulletList:
        dist = gd.Dist(
                gd.bulletList[x].X,
                gd.bulletList[x].Y, 
                gd.bulletList[x].MX, 
                gd.bulletList[x].MY)
        ## MX - DestX, MY - DestY, X и Y. Speed - speed.
        if (gd.bulletList[x].X < gd.bulletList[x].MX):
            gd.bulletList[x].X = gd.bulletList[x].speed
        if (gd.bulletList[x].X > gd.bulletList[x].MX):
            gd.bulletList[x].X -= gd.bulletList[x].speed
        if (gd.bulletList[x].Y < gd.bulletList[x].MY):
            gd.bulletList[x].Y += gd.bulletList[x].speed
        if (gd.bulletList[x].Y > gd.bulletList[x].MY):
            gd.bulletList[x].Y -= gd.bulletList[x].speed
        win.blit(spd.sprites['bullet'], (gd.bulletList[x].X, gd.bulletList[x].Y))

Create like this:

Preview

Please help me! How to create a uniform movement!

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Yagir
  • 13
  • 2
  • What exactly is the problem with your code? – mkrieger1 Mar 03 '19 at 20:47
  • See [Shooting a bullet in pygame in the direction of mouse](https://stackoverflow.com/questions/59977052/shooting-a-bullet-in-pygame-in-the-direction-of-mouse/59980344#59980344) – Rabbid76 Oct 04 '20 at 18:46

1 Answers1

1

Calculate the vector form the bullet position to the target, using pygame.math.Vector2:

tragetPos = pygame.math.Vector2(bullet.MX, bullet.MY)
bulletPos = pygame.math.Vector2(bullet.X, bullet.Y)
bulletDir = tragetPos - bulletPos

Calculate the length of the vector (pygame.math.length()). The length is the current distance from the bullet to the target:

distance = bulletDir.length()

Normalize the direction vector (pygame.math.normalize()). This means the vector becomes a Unit vector with lenght 1:

bulletDir = bulletDir.normalize()

The bullet has to move in the direction of the target by the minimum of the speed (bullet.speed) and the distance to the target (the bullet should not go beyond the target). Calculate the new position of the bullet:

bulletPos = bulletPos + bulletDir * min(distance, speed)

Finally the attributes X and Y can be set and the bullet can be blit. The function may look like this:

def Entities():

    for bullet in gd.bulletList:

        tragetPos = pygame.math.Vector2(bullet.MX, bullet.MY)
        bulletPos = pygame.math.Vector2(bullet.X, bullet.Y)
        bulletDir = tragetPos - bulletPos
        distance  = bulletDir.length()
        if distance > 0:

            bulletDir = bulletDir.normalize()
            bulletPos = bulletPos + bulletDir * min(distance, speed)

            bullet.X, bullet.Y = bulletPos
            win.blit(spd.sprites['bullet'], (int(bullet.X), int(bullet.Y)))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174