While I realize that there are quite a few posts about this on the StackOverflow forums, however none that I was able to find have a problem quite like mine. So basically, as you can probably tell from the title, I am having difficults moving an image in pygame. There are no errors, or anything of that nature, it's just that the image isn't moving. I am currently coding this in OOP style, so I will paste what is relavent.
class DisplayImage:
def __init__(self, image, pos) -> None:
self.x = pos[0]
self.y = pos[1]
self.image = pygame.image.load(image).convert()
self.rect = self.image.get_rect(center=(self.x, self.y))
def update(self, screen):
self.rect.x = self.x
self.rect.y = self.y
screen.blit(self.image, self.rect)
def checkForInput(self, event):
if(self.rect.collidepoint(event.pos)):
return True
return False
def move(self, direction):
print("moving!")
self.x += direction[0]
self.y += direction[1]
Then there is my setup:
import pygame
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()
running = True
moving = False
while running:
screen.fill("black")
ran_candy = Candy('image.png', (100, 100))
mouse_pos = pygame.mouse.get_pos()
screen.blit(ran_candy.image, (ran_candy.x, ran_candy.y))
for event in pygame.event.get():
if (event.type == pygame.QUIT):
running = False
if (event.type == pygame.MOUSEBUTTONDOWN):
if (ran_candy.checkForInput(event)):
moving = True
elif (event.type == pygame.MOUSEBUTTONUP):
moving = False
elif (event.type == pygame.MOUSEMOTION and moving):
ran_candy.move(event.rel)
pygame.display.flip()
pygame.display.update()
This should be enough for reproducability. Right now my main guess would be that it's not properly updating the class self.x and self.y coordinates when I call the function, but I'm not sure. Feel free to help.
Edit: Another "problem" that I am having with this currently is that it is not really registering that I am trying to move it. I added some print statements to print out if I am moving it (while it does not update the image) it takes a while before it prints that I am moving it. What I mean is, the pygame.MOUSEMOTION seems quite sensitive and difficult to activate, any alleviations for that aswell?
Edit: Solution: Basically all I had to do was move it out of the loop and everything worked. So I had to create the class outside the loop and it seemed to work