I have the following class:
class Enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.init()
pygame.sprite.Sprite.__init__(self)
# Basic variables
self.speed = [2,2]
# Sets up the image and Rect
self.bitmap = pygame.image.load("badguy.png")
self.bitmap.set_colorkey((0,0,0))
self.shipRect = self.bitmap.get_rect()
self.shipRect.topleft = [100,200]
def move(self, x, y):
self.shipRect.center = (x,y)
def render(self):
screen.blit(self.bitmap, (self.shipRect))
Now, I want to have it move whenever I hit an arrow key. However, there’s a big problem with my move function. It simply moves the center of the ship to the coordinates fed into the function. In case you aren’t seeing the problem, it’s that I’m trying to call it like this:
if event.key == K_RIGHT:
enemy.x += 5
if event.key == K_LEFT:
enemy.move(-5,0)
if event.key == K_UP:
enemy.move(0,5)
if event.key == K_DOWN:
enemy.move(0,-5)
I was expecting it to move my five in the direction of the key that I hit. However, it shoots to the top left of the screen because I’m making the center set at zero on one axis and +- 5 on the other axis.
What method can be used to make it move in the correct direction and still give me the ability to put the sprites at a starting position on the screen that I choose.
Any help is much appreciated.
change
moveto:This way it just increments the position by the move amount you specify.