How do I make a image move towards another? [duplicate] - python

I'm having trouble with moving sprites. I can move them in the x and y axis with no problem at all. What I can't figure out is how can I move them according to a certain angle. What I mean is, I'm trying to create a function which includes the object I'm trying to move, its speed, and its direction(which should be measured in degrees). Something like:
MovingObject(obj,speed,direction) #this is the function I'm trying to define
It's more like a "spawning function" rather than just movement... Take for example that I would like to create an object of the class "Bullet" and want it to follow certain direction (different from the x and y axis, of course)
Actually I have no clear idea of how to do such thing and I would like some advice in order to achieve so.
Thanks for reading this!
EDIT:
#Joran Beasley I tried to do what you told me...but I guess I did it wrong...
import pygame, math, time
screen=pygame.display.set_mode((320,240))
clock=pygame.time.Clock()
pygame.init()
def calculate_new_xy(old_xy,speed,angle_in_radians):
new_x = old_xy.x + (speed*math.cos(angle_in_radians))
new_y = old_xy.y + (speed*math.sin(angle_in_radians))
return new_x, new_y
class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y,direction,speed):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface((16, 16))
self.image.fill((255,0,0))
self.rect=self.image.get_rect()
self.rect.center=(x,y)
self.direction=math.radians(direction)
self.speed=speed
def update(self):
self.rect.center=calculate_new_xy(self.rect,self.speed,self.direction)
spr=pygame.sprite.Group()
bullet=Bullet(160,120,45,1); spr.add(bullet)
play=True
while play:
clock.tick(60)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
play=False
screen.fill((0,0,0))
spr.update()
spr.draw(screen)
pygame.display.flip()
pygame.quit()
The object moves but... not in the specified direction...

you just need a little basic trig
def calculat_new_xy(old_xy,speed,angle_in_radians):
new_x = old_xy.X + (speed*math.cos(angle_in_radians))
new_y = old_xy.Y + (speed*math.sin(angle_in_radians))
return new_x, new_y
--- edit ---
Here is your code from above edited to work
import pygame, math, time
screen=pygame.display.set_mode((320,240))
clock=pygame.time.Clock()
pygame.init()
def calculate_new_xy(old_xy,speed,angle_in_radians):
new_x = old_xy[0] + (speed*math.cos(angle_in_radians))
new_y = old_xy[1] + (speed*math.sin(angle_in_radians))
return new_x, new_y
class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y,direction,speed):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface((16, 16))
self.image.fill((255,0,0))
self.rect=self.image.get_rect()
self.rect.center=(x,y)
self.direction=math.radians(direction)
self.speed=speed
def update(self):
self.rect.center=calculate_new_xy(self.rect.center,self.speed,self.direction)
spr=pygame.sprite.Group()
bullet=Bullet(160,120,45,2); spr.add(bullet)
play=True
while play:
clock.tick(60)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
play=False
screen.fill((0,0,0))
spr.update()
spr.draw(screen)
pygame.display.flip()
pygame.quit()

I recommend to use vectors. To get the velocity, rotate the start direction vector Vector2(1, 0) by the angle and multiply it by the desired speed. Then just add this velocity vector to the position vector in the update method and also update the rect position to move the sprite. (Press 'a' or 'd' to rotate, mouse 1 or space to shoot.)
import pygame as pg
from pygame.math import Vector2
pg.init()
screen = pg.display.set_mode((640, 480))
screen_rect = screen.get_rect()
FONT = pg.font.Font(None, 24)
BULLET_IMAGE = pg.Surface((20, 11), pg.SRCALPHA)
pg.draw.polygon(BULLET_IMAGE, pg.Color('aquamarine1'),
[(0, 0), (20, 5), (0, 11)])
class Bullet(pg.sprite.Sprite):
def __init__(self, pos, angle):
super().__init__()
self.image = pg.transform.rotate(BULLET_IMAGE, -angle)
self.rect = self.image.get_rect(center=pos)
# To apply an offset to the start position,
# create another vector and rotate it as well.
offset = Vector2(40, 0).rotate(angle)
# Then add the offset vector to the position vector.
self.pos = Vector2(pos) + offset # Center of the sprite.
# Rotate the direction vector (1, 0) by the angle.
# Multiply by desired speed.
self.velocity = Vector2(1, 0).rotate(angle) * 9
def update(self):
self.pos += self.velocity # Add velocity to pos to move the sprite.
self.rect.center = self.pos # Update rect coords.
if not screen_rect.contains(self.rect):
self.kill()
def main():
clock = pg.time.Clock()
cannon_img = pg.Surface((40, 20), pg.SRCALPHA)
cannon_img.fill(pg.Color('aquamarine3'))
cannon = cannon_img.get_rect(center=(320, 240))
angle = 0
bullet_group = pg.sprite.Group() # Add bullets to this group.
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
elif event.type == pg.MOUSEBUTTONDOWN:
# Left button fires a bullet from center with
# current angle. Add the bullet to the bullet_group.
if event.button == 1:
bullet_group.add(Bullet(cannon.center, angle))
keys = pg.key.get_pressed()
if keys[pg.K_a]:
angle -= 3
elif keys[pg.K_d]:
angle += 3
if keys[pg.K_SPACE]:
bullet_group.add(Bullet(cannon.center, angle))
# Rotate the cannon image.
rotated_cannon_img = pg.transform.rotate(cannon_img, -angle)
cannon = rotated_cannon_img.get_rect(center=cannon.center)
bullet_group.update()
# Draw
screen.fill((30, 40, 50))
screen.blit(rotated_cannon_img, cannon)
bullet_group.draw(screen)
txt = FONT.render('angle {:.1f}'.format(angle), True, (150, 150, 170))
screen.blit(txt, (10, 10))
pg.display.update()
clock.tick(30)
if __name__ == '__main__':
main()
pg.quit()
Regarding the code in your added example, the easiest solution is to calculate the speed_x and speed_y ("velocity" would be more fitting) in the __init__ method and then just update the self.rect.x and y attributes in the update method.
import math
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
BULLET_IMAGE = pygame.Surface((20, 11), pygame.SRCALPHA)
pygame.draw.polygon(BULLET_IMAGE, pygame.Color('aquamarine1'),
[(0, 0), (20, 5), (0, 11)])
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, angle, speed):
pygame.sprite.Sprite.__init__(self)
# Rotate the bullet image (negative angle because y-axis is flipped).
self.image = pygame.transform.rotate(BULLET_IMAGE, -angle)
self.rect = self.image.get_rect(center=(x, y))
angle = math.radians(angle)
self.speed_x = speed * math.cos(angle)
self.speed_y = speed * math.sin(angle)
def update(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
spr = pygame.sprite.Group()
bullet = Bullet(10, 10, 60, 3)
bullet2 = Bullet(10, 10, 30, 3)
spr.add(bullet, bullet2)
play = True
while play:
clock.tick(60)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
play = False
screen.fill((30,30,40))
spr.update()
spr.draw(screen)
pygame.display.flip()
pygame.quit()
There's a problem, because pygame.Rects can only have ints as the x and y attributes, so the movement won't be 100% correct. To solve this problem, you need to store the coords/position of the sprite in separate variables, add the speed to them and afterwards update the rect:
# In `__init__`.
self.pos_x = x
self.pos_y = y
def update(self):
self.pos_x += self.speed_x
self.pos_y += self.speed_y
self.rect.center = (self.pos_x, self.pos_y)

If you are using Pygame, I suggest to use pygame.math.Vector2 for this task. Set a direction vector from its Polar coordinates (speed, angle_in_degrees) with from_polar(). Add this vector to the current position of the bullet. This is more comprehensible than using sin and cos:
def calculate_new_xy(old_xy, speed, angle_in_degrees):
move_vec = pygame.math.Vector2()
move_vec.from_polar((speed, angle_in_degrees))
return old_xy + move_vec
Be aware, that a pygame.Rect can only store integer coordinates. This is because a pygame.Rect is supposed to represent an area on the screen:
The coordinates for Rect objects are all integers. [...]
If you want the bullet to go straight in a certain direction at an angle that is not divisible by 45 °, you must store object positions with floating point accuracy. You have to store the location of the object in separate variables respectively attributes and to synchronize the pygame.Rect object. round the coordinates and assign it to the location (e.g. .topleft) of the rectangle:
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, direction, speed):
# [...]
self.rect = self.image.get_rect(center = (x, y))
self.pos = (x, y)
def update(self, screen):
self.pos = calculate_new_xy(self.pos, self.speed, -self.direction)
self.rect.center = round(self.pos[0]), round(self.pos[1])
See also Move towards target
Minimal example
import pygame
def calculate_new_xy(old_xy, speed, angle_in_degrees):
move_vec = pygame.math.Vector2()
move_vec.from_polar((speed, angle_in_degrees))
return old_xy + move_vec
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, direction, speed):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((16, 8), pygame.SRCALPHA)
self.image.fill((255, 0, 0))
self.image = pygame.transform.rotate(self.image, direction)
self.rect = self.image.get_rect(center = (x, y))
self.pos = (x, y)
self.direction = direction
self.speed = speed
def update(self, screen):
self.pos = calculate_new_xy(self.pos, self.speed, -self.direction)
self.rect.center = round(self.pos[0]), round(self.pos[1])
if not screen.get_rect().colliderect(self.rect):
self.kill()
pygame.init()
screen = pygame.display.set_mode((320,240))
clock = pygame.time.Clock()
spr = pygame.sprite.Group()
play = True
frame_count = 0
while play:
clock.tick(60)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
play = False
spr.update(screen)
if (frame_count % 10) == 0:
spr.add(Bullet(*screen.get_rect().center, frame_count, 2))
frame_count += 1
screen.fill((0,0,0))
spr.draw(screen)
pygame.draw.circle(screen, (64, 128, 255), screen.get_rect().center, 10)
pygame.display.flip()
pygame.quit()
exit()

Related

Why is param moveY not apearing? Pygame update method

I'm trying to play around with pygame and I can draw an image as a sprite on the screen. I'm trying to move the sprite around with WASD by changing the x and y variables.
When I run the program, the sprite draws but doesn't move when I press the correct keys.
EDIT: I added an update method and the moveY param is saying it is not there, even though it clearly is, why is this?
Here's the code:
import pygame
pygame.init()
screen = pygame.display.set_mode((750, 750))
BLACK = (0, 0, 0)
WHITE = (255,255,255)
RED = (255,0,0)
class Sprite(pygame.sprite.Sprite):
def __init__(self, pos):
super(Sprite, self).__init__()
self.image = demon
self.pos = [x,y]
self.rect = self.image.get_rect(center = pos)
def update(self, moveX, moveY):
pygame.sprite.Sprite.update(self)
moveXY = [moveX,moveY]
Sprite.pos[x] += moveXY[moveX]
Sprite.pos[y] += moveXY[moveY]
all_sprites_list = pygame.sprite.Group()
demon = pygame.image.load("C:/programming/doomman/cacodemon.png").convert_alpha()
x = 300
y = 300
my_sprite = Sprite((x, y))
all_sprites_list.add(my_sprite)
clock = pygame.time.Clock()
pygame.display.set_caption("Demon Dance")
carryOn = True
while carryOn == True:
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type==pygame.QUIT:
carryOn=False
elif event.type == pygame.KEYDOWN:
if keys[pygame.K_w]:
Sprite.update(0, 50)
if keys[pygame.K_s]:
Sprite.update(0, -50)
if keys[pygame.K_d]:
Sprite.update(50, 0)
if keys[pygame.K_a]:
Sprite.update(-50, 0)
pygame.display.flip()
clock.tick(60)
all_sprites_list.draw(screen)
See pygame.sprite.Group.draw:
Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect for the position.
Therefore you need to update the rect attribute after changing the position (pos) of the Sprite:
class Sprite(pygame.sprite.Sprite):
def __init__(self, pos):
super(Sprite, self).__init__()
self.image = demon
self.pos = [pos[0], pos[1]]
self.rect = self.image.get_rect(center = pos)
def update(self, moveX, moveY):
Sprite.pos[x] += moveX
Sprite.pos[y] += moveY
self.rect = self.image.get_rect(center = pos)
You don't actually need the pos attribute at all. You can move the Sprite by changing the position stored in rect:
class Sprite(pygame.sprite.Sprite):
def __init__(self, pos):
super(Sprite, self).__init__()
self.image = demon
self.rect = self.image.get_rect(center = pos)
def update(self, moveX, moveY):
self.rect.x += moveX
self.rect.y += moveY
Additionally update is an instance method. You need to call it with the object instead of the class:
if keys[pygame.K_w]:
my_sprite.update(0, 50)
if keys[pygame.K_s]:
my_sprite.update(0, -50)
if keys[pygame.K_d]:
my_sprite.update(50, 0)
if keys[pygame.K_a]:
my_sprite.update(-50, 0)

Pygame Transformation: rotate shape on key press

I'm fairly new to Pygame, and can't seem to find a solid answer on this. I have a shape, specifically an ellipse, that I want to rotate both left and right. The key bind would be a and d, as the arrow keys are already binded to move left and right on an x,y axis.
I know that it involves pygame.transform.rotate, however I can't seem to implement this right.
def main():
#Setup basic variables and methods for pygame
pygame.init()
windowWidth = 800
windowHeight = 700
fps = 45
clock = pygame.time.Clock()
gameWindow = pygame.display.set_mode((windowWidth, windowHeight))
surface = pygame.Surface((50,50))
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
shipX = windowWidth/2
shipY = windowWidth/2
shipSpeed = 4
while(True):
pygame.draw.ellipse(gameWindow, WHITE, (shipX, shipY, 20, 30))
#Monitor the FPS of the game
clock.tick(fps)
for event in pygame.event.get():
# ________________________________________
if event.type == pygame.QUIT:
gameExit()
rotate = 0
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP] and shipY > shipSpeed: shipY -= shipSpeed
if pressed[pygame.K_DOWN] and shipY < windowHeight - shipSpeed - 20: shipY += shipSpeed
if pressed[pygame.K_LEFT] and shipX > shipSpeed:shipX -= shipSpeed
if pressed[pygame.K_RIGHT] and shipX < windowWidth - shipSpeed - 20: shipX += shipSpeed
if pressed[ord('a')]: rotate = pygame.transform.rotate(surface, -20)
if pressed[ord('d')]: rotate = pygame.transform.rotate(surface, 20)
gameWindow.fill(BLACK)
# 'flip' display - always after drawing...
pygame.display.flip()
The expected result is that the shape will change it's angle, and then move accordingly.
Again, I'm very new to pygame, so any detailed help would be appreciated.
Your problem is that you draw the ellipse directly on the screen, but you should draw your ellipse on another Surface.
Then you can rotate that new Surface with pygame.transform.rotate.
Here's a simple example:
import pygame
import random
def main():
pygame.init()
screen = pygame.display.set_mode((500, 500))
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
surface = pygame.Surface((100, 200))
surface.set_colorkey((2, 3, 4))
surface.fill((2, 3, 4))
rect = surface.get_rect(center=(100, 100))
pygame.draw.ellipse(surface, pygame.Color('white'), (0, 0, 100, 200))
angle = 0
dt = 0
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: rect.move_ip(0, -5)
if pressed[pygame.K_DOWN]: rect.move_ip(0, 5)
if pressed[pygame.K_LEFT]: rect.move_ip(-5, 0)
if pressed[pygame.K_RIGHT]: rect.move_ip(5, 0)
if pressed[pygame.K_a]: angle += 1
if pressed[pygame.K_d]: angle -= 1
rotated = pygame.transform.rotate(surface, angle)
rect = rotated.get_rect(center=rect.center)
rect.clamp_ip(screen_rect)
screen.fill(pygame.Color('dodgerblue'))
screen.blit(rotated, rect.topleft)
pygame.display.update()
dt = clock.tick(60)
if __name__ == '__main__':
main()
Note that I use a Rect to store the position of the object because it's easy then to rotate the Surface around its center (by setting its center attribute), and to ensure the Surface does not go outside the screen (by using clamp_ip).
Also, it's important to always rotate the source Surface, and not the already rotated Surface. Otherwise, you'll get distortions.
Note that we have three things here: an image, a position, and some behaviour logic. Whenever you see these things together, consider putting them together into a class. Pygame already offers a nice class for this, called Sprite.
Here's the same example, but Sprite-based:
import pygame
import random
class Thingy(pygame.sprite.Sprite):
def __init__(self, area):
super().__init__()
# image is what get's painted on the screen
self.image = pygame.Surface((100, 200))
self.image.set_colorkey((2, 3, 4))
self.image.fill((2, 3, 4))
pygame.draw.ellipse(self.image, pygame.Color('white'), (0, 0, 100, 200))
# we keep a reference to the original image
# since we use that for rotation to prevent distortions
self.original = self.image.copy()
# rect is used to determine the position of a sprite on the screen
# the Rect class also offers a lot of useful functions
self.rect = self.image.get_rect(center=(100, 100))
self.angle = 0
self.area = area
def update(self, events, dt):
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: self.rect.move_ip(0, -5)
if pressed[pygame.K_DOWN]: self.rect.move_ip(0, 5)
if pressed[pygame.K_LEFT]: self.rect.move_ip(-5, 0)
if pressed[pygame.K_RIGHT]: self.rect.move_ip(5, 0)
if pressed[pygame.K_a]: self.angle += 1
if pressed[pygame.K_d]: self.angle -= 1
# let's rotate the image, but ensure that we keep the center position
# so it doesn't "jump around"
self.image = pygame.transform.rotate(self.original, self.angle)
self.rect = self.image.get_rect(center=self.rect.center)
self.rect.clamp_ip(self.area)
def main():
pygame.init()
screen = pygame.display.set_mode((500, 500))
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
sprites = pygame.sprite.Group(Thingy(screen_rect))
dt = 0
while True:
# nice clean main loop
# all game logic goes into the sprites
# handle "global" events
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
# update all sprites
sprites.update(events, dt)
# draw everything
screen.fill(pygame.Color('dodgerblue'))
sprites.draw(screen)
pygame.display.update()
dt = clock.tick(60)
if __name__ == '__main__':
main()
You should make a class for your object:
class myRect(pygame.Surface):
def __init__(self, parent, xpos, ypos, width, height):
super(myRect, self).__init__(width, height)
self.xpos = xpos
self.ypos = ypos
self.parent = parent
def update(self, parent):
parent.blit(self, (self.xpos, self.ypos))
def rotate(self, angle):
#(your rotation code goes here)

how to rotate a bullet according to the player's rotation

I've finally figured out how to shoot bullets but now I want to rotate the origin of the bullets on the rotation of the players head. Now it's only shooting straight on the x line. The mobs are working fine. I only need to add in collision and the bullet that is rotating on the player's angle. I will do the collision myself although If anyone could hint me it would be appreciated. My main focus right now is to rotate the bullet according to the player's angle and 'kill' the bullet when it flies off screen.
import pygame
import random
import math
GRAD = math.pi / 180
black = (0,0,0)
class Config(object):
fullscreen = True
width = 1366
height = 768
fps = 60
class Player(pygame.sprite.Sprite): #player class
maxrotate = 180
down = (pygame.K_DOWN)
up = (pygame.K_UP)
def __init__(self, startpos=(102,579), angle=0):
super().__init__()
self.pos = list(startpos)
self.image = pygame.image.load('BigShagHoofdzzz.gif')
self.orig_image = self.image
self.rect = self.image.get_rect(center=startpos)
self.angle = angle
def update(self, seconds):
pressedkeys = pygame.key.get_pressed()
if pressedkeys[self.down]:
self.angle -= 2
self.rotate_image()
if pressedkeys[self.up]:
self.angle += 2
self.rotate_image()
def rotate_image(self):#rotating player image
self.image = pygame.transform.rotate(self.orig_image, self.angle)
self.rect = self.image.get_rect(center=self.rect.center)
class Mob(pygame.sprite.Sprite):#monster sprite
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('Monster1re.png')
self.rect = self.image.get_rect()
self.rect.x = 1400
self.rect.y = random.randrange(500,600)
self.speedy = random.randrange(-8, -1)
def update(self):
self.rect.x += self.speedy
if self.rect.x < -100 :
self.rect.x = 1400
self.speedy = random.randrange(-8, -1)
class Bullet(pygame.sprite.Sprite):#bullet sprite needs to rotate according to player's angle.
""" This class represents the bullet . """
def __init__(self):
# Call the parent class (Sprite) constructor
super().__init__()
self.image = pygame.image.load('lols.png').convert()
self.image.set_colorkey(black)
self.rect = self.image.get_rect()
def update(self):
""" Move the bullet. """
self.rect.x += 10
#end class
player = Player()
mobs = []
for x in range(0,10):
mob = Mob()
mobs.append(mob)
print(mobs)
all_sprites_list = pygame.sprite.Group()
allgroup = pygame.sprite.LayeredUpdates()
allgroup.add(player)
for mob in mobs:
all_sprites_list.add(mob)
def main():
#game
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.mixer.init()
pygame.init()
screen=pygame.display.set_mode((Config.width, Config.height),
pygame.FULLSCREEN)
background = pygame.image.load('BGGameBig.png')
sound = pygame.mixer.Sound("shoot2.wav")
bullet_list = pygame.sprite.Group
clock = pygame.time.Clock()
FPS = Config.fps
mainloop = True
while mainloop:
millisecond = clock.tick(Config.fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
if event.key == pygame.K_SPACE: #Bullet schiet knop op space
bullet = Bullet()
bullet.rect.x = player.rect.x
bullet.rect.y = player.rect.y
all_sprites_list.add(bullet)
bullet_list.add(bullet)
sound.play()
if event.key == pygame.K_ESCAPE:
mailoop = False
pygame.display.set_caption("hi")
allgroup.update(millisecond)
all_sprites_list.update()
screen.blit(background, (0,0))
allgroup.draw(screen)
all_sprites_list.draw(screen)
pygame.display.flip()
if __name__ == '__main__':
main()
pygame.quit()
So It needs to rotate on the players self.angle which is updated when pressing key up or key down.
You need to use trigonometry or vectors to calculate the velocity of the bullet (I use trig here). Pass the angle of the player to the Bullet and then use math.cos and math.sin with the negative angle to get the direction of the bullet and scale it by the desired speed. The actual position has to be stored in a list or vector, because pygame.Rects can only have ints as their coordinates.
class Bullet(pygame.sprite.Sprite):
"""This class represents the bullet."""
def __init__(self, pos, angle):
super().__init__()
# Rotate the image.
self.image = pygame.transform.rotate(your_bullet_image, angle)
self.rect = self.image.get_rect()
speed = 5 # 5 pixels per frame.
# Use trigonometry to calculate the velocity.
self.velocity_x = math.cos(math.radians(-angle)) * speed
self.velocity_y = math.sin(math.radians(-angle)) * speed
# Store the actual position in a list or a vector.
self.pos = list(pos)
def update(self):
""" Move the bullet. """
self.pos[0] += self.velocity_x
self.pos[1] += self.velocity_y
# Update the position of the rect as well.
self.rect.center = self.pos
# In the event loop.
if event.key == pygame.K_SPACE:
# Pass the position and angle of the player.
bullet = Bullet(player.rect.center, player.angle)
all_sprites_list.add(bullet)
bullet_list.add(bullet)

How do you move a sprite in pygame?

I know that this question has already been answered in other forms, but I can't seem to make it work for my game. I'm trying to make the sprite move and keep him in the place he moved to. This is part of my code:
class player(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
def draw(self, x, y):
player = pygame.image.load("stand_down.png").convert_alpha()
player = pygame.transform.scale(player, (100, 200))
screen.blit(player, (x, y))
pygame.display.update()
for event in pygame.event.get():
key = pygame.key.get_pressed()
if event.type == KEYDOWN :
if key [K_LEFT] :
player = pygame.image.load("standleft.png").convert_alpha()
player = pygame.transform.scale(player, (100, 200))
x -= 50
screen.blit(player, (x, y))
pygame.display.update()
pygame.sprite.Sprite.update(player)
if key [K_RIGHT]:
player = pygame.image.load("standright.png").convert_alpha()
player = pygame.transform.scale(player, (100, 200))
x += 50
screen.blit(player, (x, y))
pygame.display.update()
pygame.sprite.Sprite.update(player)
def update(self):
pygame.sprite.Sprite.update(player)
And then this is part of my main function:
player.draw(screen, x, y)
player.update(screen)
I've tried everything I can think of, but the player just keeps flashing at a different point, then returning to the previous position. If you could help, it would be much appreciated!
I can't test it but I would do this
# --- classes ---
class Player(pygame.sprite.Sprite): # UpperCaseName for class
def __init__(self, x, y):
super().__init__()
temp_image = pygame.image.load("stand_down.png").convert_alpha()
self.image_down = pygame.transform.scale(temp_image, (100, 200))
temp_image = pygame.image.load("standleft.png").convert_alpha()
self.image_left = pygame.transform.scale(temp_image, (100, 200))
temp_image = pygame.image.load("standright.png").convert_alpha()
self.image_right = pygame.transform.scale(temp_image, (100, 200))
self.image = self.image_down
# keep position and size in pygame.Rect()
# to use it in collision checking
self.rect = self.image.get_rect(x=x, y=y)
def draw(self, screen):
screen.blit(self.image, self.rect)
def handle_event(self):#, event)
self.image = self.image_down
key = pygame.key.get_pressed()
if key[K_LEFT]:
self.rect.x -= 50
self.image = self.image_left
if key[K_RIGHT]:
self.rect.x += 50
self.image = self.image_right
def update(self, enemy):
# check collision with eneny
if self.rect.colliderect(enemy.rect):
print("I'm killed by enemy")
# --- main ---
player = Player(400, 400)
enemy = Enemy(100, 100)
while True:
# - events -
for event in pygame.event.get():
#player.handle_event(event)
player.handle_event()
# - updates -
enemy.update()
player.update(enemy)
# - draws -
screen.fill( (0,0,0) )
player.draw(screen)
enemy.draw(screen)
pygame.display.update()

How to move a sprite according to an angle in Pygame

I'm having trouble with moving sprites. I can move them in the x and y axis with no problem at all. What I can't figure out is how can I move them according to a certain angle. What I mean is, I'm trying to create a function which includes the object I'm trying to move, its speed, and its direction(which should be measured in degrees). Something like:
MovingObject(obj,speed,direction) #this is the function I'm trying to define
It's more like a "spawning function" rather than just movement... Take for example that I would like to create an object of the class "Bullet" and want it to follow certain direction (different from the x and y axis, of course)
Actually I have no clear idea of how to do such thing and I would like some advice in order to achieve so.
Thanks for reading this!
EDIT:
#Joran Beasley I tried to do what you told me...but I guess I did it wrong...
import pygame, math, time
screen=pygame.display.set_mode((320,240))
clock=pygame.time.Clock()
pygame.init()
def calculate_new_xy(old_xy,speed,angle_in_radians):
new_x = old_xy.x + (speed*math.cos(angle_in_radians))
new_y = old_xy.y + (speed*math.sin(angle_in_radians))
return new_x, new_y
class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y,direction,speed):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface((16, 16))
self.image.fill((255,0,0))
self.rect=self.image.get_rect()
self.rect.center=(x,y)
self.direction=math.radians(direction)
self.speed=speed
def update(self):
self.rect.center=calculate_new_xy(self.rect,self.speed,self.direction)
spr=pygame.sprite.Group()
bullet=Bullet(160,120,45,1); spr.add(bullet)
play=True
while play:
clock.tick(60)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
play=False
screen.fill((0,0,0))
spr.update()
spr.draw(screen)
pygame.display.flip()
pygame.quit()
The object moves but... not in the specified direction...
you just need a little basic trig
def calculat_new_xy(old_xy,speed,angle_in_radians):
new_x = old_xy.X + (speed*math.cos(angle_in_radians))
new_y = old_xy.Y + (speed*math.sin(angle_in_radians))
return new_x, new_y
--- edit ---
Here is your code from above edited to work
import pygame, math, time
screen=pygame.display.set_mode((320,240))
clock=pygame.time.Clock()
pygame.init()
def calculate_new_xy(old_xy,speed,angle_in_radians):
new_x = old_xy[0] + (speed*math.cos(angle_in_radians))
new_y = old_xy[1] + (speed*math.sin(angle_in_radians))
return new_x, new_y
class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y,direction,speed):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface((16, 16))
self.image.fill((255,0,0))
self.rect=self.image.get_rect()
self.rect.center=(x,y)
self.direction=math.radians(direction)
self.speed=speed
def update(self):
self.rect.center=calculate_new_xy(self.rect.center,self.speed,self.direction)
spr=pygame.sprite.Group()
bullet=Bullet(160,120,45,2); spr.add(bullet)
play=True
while play:
clock.tick(60)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
play=False
screen.fill((0,0,0))
spr.update()
spr.draw(screen)
pygame.display.flip()
pygame.quit()
I recommend to use vectors. To get the velocity, rotate the start direction vector Vector2(1, 0) by the angle and multiply it by the desired speed. Then just add this velocity vector to the position vector in the update method and also update the rect position to move the sprite. (Press 'a' or 'd' to rotate, mouse 1 or space to shoot.)
import pygame as pg
from pygame.math import Vector2
pg.init()
screen = pg.display.set_mode((640, 480))
screen_rect = screen.get_rect()
FONT = pg.font.Font(None, 24)
BULLET_IMAGE = pg.Surface((20, 11), pg.SRCALPHA)
pg.draw.polygon(BULLET_IMAGE, pg.Color('aquamarine1'),
[(0, 0), (20, 5), (0, 11)])
class Bullet(pg.sprite.Sprite):
def __init__(self, pos, angle):
super().__init__()
self.image = pg.transform.rotate(BULLET_IMAGE, -angle)
self.rect = self.image.get_rect(center=pos)
# To apply an offset to the start position,
# create another vector and rotate it as well.
offset = Vector2(40, 0).rotate(angle)
# Then add the offset vector to the position vector.
self.pos = Vector2(pos) + offset # Center of the sprite.
# Rotate the direction vector (1, 0) by the angle.
# Multiply by desired speed.
self.velocity = Vector2(1, 0).rotate(angle) * 9
def update(self):
self.pos += self.velocity # Add velocity to pos to move the sprite.
self.rect.center = self.pos # Update rect coords.
if not screen_rect.contains(self.rect):
self.kill()
def main():
clock = pg.time.Clock()
cannon_img = pg.Surface((40, 20), pg.SRCALPHA)
cannon_img.fill(pg.Color('aquamarine3'))
cannon = cannon_img.get_rect(center=(320, 240))
angle = 0
bullet_group = pg.sprite.Group() # Add bullets to this group.
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
elif event.type == pg.MOUSEBUTTONDOWN:
# Left button fires a bullet from center with
# current angle. Add the bullet to the bullet_group.
if event.button == 1:
bullet_group.add(Bullet(cannon.center, angle))
keys = pg.key.get_pressed()
if keys[pg.K_a]:
angle -= 3
elif keys[pg.K_d]:
angle += 3
if keys[pg.K_SPACE]:
bullet_group.add(Bullet(cannon.center, angle))
# Rotate the cannon image.
rotated_cannon_img = pg.transform.rotate(cannon_img, -angle)
cannon = rotated_cannon_img.get_rect(center=cannon.center)
bullet_group.update()
# Draw
screen.fill((30, 40, 50))
screen.blit(rotated_cannon_img, cannon)
bullet_group.draw(screen)
txt = FONT.render('angle {:.1f}'.format(angle), True, (150, 150, 170))
screen.blit(txt, (10, 10))
pg.display.update()
clock.tick(30)
if __name__ == '__main__':
main()
pg.quit()
Regarding the code in your added example, the easiest solution is to calculate the speed_x and speed_y ("velocity" would be more fitting) in the __init__ method and then just update the self.rect.x and y attributes in the update method.
import math
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
BULLET_IMAGE = pygame.Surface((20, 11), pygame.SRCALPHA)
pygame.draw.polygon(BULLET_IMAGE, pygame.Color('aquamarine1'),
[(0, 0), (20, 5), (0, 11)])
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, angle, speed):
pygame.sprite.Sprite.__init__(self)
# Rotate the bullet image (negative angle because y-axis is flipped).
self.image = pygame.transform.rotate(BULLET_IMAGE, -angle)
self.rect = self.image.get_rect(center=(x, y))
angle = math.radians(angle)
self.speed_x = speed * math.cos(angle)
self.speed_y = speed * math.sin(angle)
def update(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
spr = pygame.sprite.Group()
bullet = Bullet(10, 10, 60, 3)
bullet2 = Bullet(10, 10, 30, 3)
spr.add(bullet, bullet2)
play = True
while play:
clock.tick(60)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
play = False
screen.fill((30,30,40))
spr.update()
spr.draw(screen)
pygame.display.flip()
pygame.quit()
There's a problem, because pygame.Rects can only have ints as the x and y attributes, so the movement won't be 100% correct. To solve this problem, you need to store the coords/position of the sprite in separate variables, add the speed to them and afterwards update the rect:
# In `__init__`.
self.pos_x = x
self.pos_y = y
def update(self):
self.pos_x += self.speed_x
self.pos_y += self.speed_y
self.rect.center = (self.pos_x, self.pos_y)
If you are using Pygame, I suggest to use pygame.math.Vector2 for this task. Set a direction vector from its Polar coordinates (speed, angle_in_degrees) with from_polar(). Add this vector to the current position of the bullet. This is more comprehensible than using sin and cos:
def calculate_new_xy(old_xy, speed, angle_in_degrees):
move_vec = pygame.math.Vector2()
move_vec.from_polar((speed, angle_in_degrees))
return old_xy + move_vec
Be aware, that a pygame.Rect can only store integer coordinates. This is because a pygame.Rect is supposed to represent an area on the screen:
The coordinates for Rect objects are all integers. [...]
If you want the bullet to go straight in a certain direction at an angle that is not divisible by 45 °, you must store object positions with floating point accuracy. You have to store the location of the object in separate variables respectively attributes and to synchronize the pygame.Rect object. round the coordinates and assign it to the location (e.g. .topleft) of the rectangle:
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, direction, speed):
# [...]
self.rect = self.image.get_rect(center = (x, y))
self.pos = (x, y)
def update(self, screen):
self.pos = calculate_new_xy(self.pos, self.speed, -self.direction)
self.rect.center = round(self.pos[0]), round(self.pos[1])
See also Move towards target
Minimal example
import pygame
def calculate_new_xy(old_xy, speed, angle_in_degrees):
move_vec = pygame.math.Vector2()
move_vec.from_polar((speed, angle_in_degrees))
return old_xy + move_vec
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, direction, speed):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((16, 8), pygame.SRCALPHA)
self.image.fill((255, 0, 0))
self.image = pygame.transform.rotate(self.image, direction)
self.rect = self.image.get_rect(center = (x, y))
self.pos = (x, y)
self.direction = direction
self.speed = speed
def update(self, screen):
self.pos = calculate_new_xy(self.pos, self.speed, -self.direction)
self.rect.center = round(self.pos[0]), round(self.pos[1])
if not screen.get_rect().colliderect(self.rect):
self.kill()
pygame.init()
screen = pygame.display.set_mode((320,240))
clock = pygame.time.Clock()
spr = pygame.sprite.Group()
play = True
frame_count = 0
while play:
clock.tick(60)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
play = False
spr.update(screen)
if (frame_count % 10) == 0:
spr.add(Bullet(*screen.get_rect().center, frame_count, 2))
frame_count += 1
screen.fill((0,0,0))
spr.draw(screen)
pygame.draw.circle(screen, (64, 128, 255), screen.get_rect().center, 10)
pygame.display.flip()
pygame.quit()
exit()

Categories