ketan ch
ketan ch

Reputation: 39

moving rectangle back and forth automatically

how can i make a rectangle in pygame to move on its own or move automatically in python without using for loop. i can make it go forward but cannot make it to come back without ifor loop and it is causing problem when i try to move my other rectangle using keys.

import pygame
import time
pygame.init()

win=pygame.display.set_mode((600,400))
pygame.display.set_caption('game trial')

x=300
y=300
true=True

x1=20
y1=100
vel=4

def draw():
    global x
    if x<550:
        x+=10
    elif x==550:
        for i in range(550):
            x-=1
            win.fill('black')
            pygame.draw.rect(win,('blue'),(x1,y1,50,50))
            pygame.draw.rect(win,('red'),(x,y,50,50))
            pygame.display.update()
            time.sleep(.003)
    win.fill('black')
    pygame.draw.rect(win,('red'),(x,y,50,50))
    pygame.draw.rect(win,('blue'),(x1,y1,50,50))
    pygame.display.update() 

clock=pygame.time.Clock()
while true:
    clock.tick(30)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
          true=False
          
    key=pygame.key.get_pressed()
    
    if [pygame.K_LEFT]:
        x1-=4
    elif [pygame.K_RIGHT]:
        x1+=4
          
    draw()
    
          
pygame.quit()

Upvotes: 2

Views: 451

Answers (1)

Rabbid76
Rabbid76

Reputation: 211249

Add the velocity (vel) to the object's position (x) in every frame. Invert the velocity (vel*= -1) when the object needs to change the direction:

def draw():
    global x, vel
    x += vel
    if x <= 0 or x >= 550:
        vel *= -1
    
    win.fill('black')
    pygame.draw.rect(win,('red'),(x,y,50,50))
    pygame.draw.rect(win,('blue'),(x1,y1,50,50))
    pygame.display.update() 

Upvotes: 1

Related Questions