Reputation: 39
i want to make my block move up and down move on its own but its not moving as every time the while loop runs the value resets to 400. I have a similar program where i apply same concept for x direction and it works but this doesn't work. Here is the code:
class Level4():
def __init__(self):
self.y=400
self.vel=10
def platform(self):
self.move()
pygame.draw.rect(win, (200, 85, 20), (400, self.y, 150, 20))
def move(self):
self.y-=self.vel
if self.y<10 or self.y > 400:
self.vel*=-1
pygame.display.update()
Upvotes: 0
Views: 1574
Reputation: 210909
I recommend to use pygame.Rect
objects. Minimal example:
import pygame
class Level():
def __init__(self, rect, yrange, vel):
self.rect = pygame.Rect(rect)
self.yrange = yrange
self.vel = vel
self.direction = -1
def move(self):
self.rect.y += self.vel * self.direction
if self.rect.top <= self.yrange[0]:
self.rect.top = self.yrange[0]
self.direction = 1
if self.rect.bottom >= self.yrange[1]:
self.rect.bottom = self.yrange[1]
self.direction = -1
def draw(self, surf):
pygame.draw.rect(surf, (200, 85, 20), self.rect)
pygame.init()
win = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
block = Level((200, 400, 150, 20), [10, 400], 5)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
block.move()
win.fill(0)
block.draw(win)
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
Upvotes: 1