Reputation: 39
I'm trying to make a sprite that moves down at a constant pace, using pygame and random. But unfortunately, the sprite just stays in one place. The issue is the method itemMover(). It does not update the value of the attribute for the instance (debris1, at the bottom), so every time, straight after the y value gets increased by the speed value it gets reset to the original value... which causes the sprite to just standstill. I don't know why it isn't updating the attribute.
import pygame
import random
# variables
mainWindow = pygame.display.set_mode((800, 600))
posX = random.randint(0,800)
posY = 0
#speedXRight = 0.5
#speedXLeft = -0.5
# images
sprite = pygame.image.load("rockred.png")
xval = random.randint(50, 750)
ypos = 0
yspeed = 0.5
class item:
def __init__(self, xpos, ypos, yspeed):
self.xpos = xpos
self.ypos = ypos
self.yspeed = yspeed
# below method not working as intended
def itemMover(self, win, val):
############HELP HERE
print(self.ypos)
self.ypos += self.yspeed
############HELP HERE
print(self.xpos, self.ypos)
win.blit(val, (self.xpos, self.ypos))
mainLoop = True
while mainLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainLoop = False
#keycode.Main = False
debris1 = item(xval, 0, 0.5)
debris1.itemMover(mainWindow, sprite)
pygame.display.update()
output:
0
167 0.5
0
167 0.5
0
167 0.5
0
167 0.5
0
167 0.5
0
167 0.5
0
167 0.5
0
167 0.5
also a window with a sprite which stays still.
Upvotes: 1
Views: 418
Reputation: 881
The reason is that each time on the loop , you re create the object debrise1 with ypos=0 and yspeed=0.5 , so when you execute the method itemMover() it will always display the same changes , what you have to do is to create the object out of the loop , and what should be inside the loop is the methode itemMover() only , like this :
mainLoop = True
debris1 = item(xval, 0, 0.5)
while mainLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainLoop = False
#keycode.Main = False
debris1.itemMover(mainWindow, sprite)
pygame.display.update()
Upvotes: 1
Reputation: 211278
the method itemMover
would work, but you recreate the object debris1
continuously in the loop. Hence the object starts at the begin in each frame.
Create the object before the application loop and move the object in the loop.
Further more you have to clear the display by pygame.Surface.fill()
, before you draw the object:
debris1 = item(xval, 0, 0.5)
mainLoop = True
while mainLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainLoop = False
mainWindow.fill(0)
debris1.itemMover(mainWindow, sprite)
pygame.display.update()
Upvotes: 2