am I missing something? I'm trying to make a sprite follow the mouse, but when I try to return the position of the ship from the sprite to compare it with the mouse position x, y are totally ignored. I have done this but keeping all the code within the sprite but for some reason it messes up the collide in pygame. Please help there's got to be a way of getting x and y out of the class!
import pygame
speed = 10
move_right = False
move_left = False
move_down = False
move_up = False
clock = pygame.time.Clock()
FPS = 60
GREEN = (0, 255, 0)
screen = pygame.display.set_mode((800, 800))
x, y = pygame.mouse.get_pos()
class Spaceship(pygame.sprite.Sprite):
def __init__(self, x, y, scale):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("ship.png")
self.image = pygame.transform.scale(self.image, (int(self.image.get_width() * scale), int(self.image.get_height() * scale)))
self.rect = self.image.get_rect()
self.rect.center = [x, y]
self.speed = 5
def move(self, move_right, move_left, move_down, move_up, x, y):
dx = 0
dy = 0
if move_right:
dx = self.speed
if move_left:
dx = -self. speed
if move_down:
dy = self.speed
if move_up:
dy = -self.speed
self.rect.x += dx
self.rect.y += dy
if self.rect.x >= 790:
self.rect.x = 790
if self.rect.x <= 10:
self.rect.x = 10
if self.rect.y <= 10:
self.rect.y = 10
if self.rect.y >= 790:
self.rect.y = 790
x = self.rect.x
y = self.rect.y
return x, y
def draw(self):
pygame.draw.rect(screen,(GREEN), self.rect, 2)
screen.blit(self.image, self.rect)
ship = Spaceship(x, y, 1)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pos = pygame.mouse.get_pos()
dx = (pos[0])
dy = (pos[1])
clock.tick(FPS)
if x < dx:
move_right = True
else: move_right = False
if x > dx:
move_left = True
else: move_left = False
if y < dy:
move_down = True
else: move_down = False
if y > dy:
move_up = True
else: move_up = False
print(dx, dy)
ship.move(move_right, move_left, move_down, move_up, x, y)
ship.draw()
pygame.display.update()
pygame.quit()