Reputation: 13
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:
Please help me! How to create a uniform movement!
Upvotes: 0
Views: 103
Reputation: 210938
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)))
Upvotes: 1