Why does my cube bounce at the left side but not at the right side?

Question:

import pygame
import sys

def main():
    x=375
    y=400
    y_velocity = 0
    acceleration = 0.1
    bg_color=(183,255,183)
    shape_color=(0,255,255)
    x_minus = None
    pygame.init()
    DISPLAY = pygame.display.set_mode((800,800))
    icon = pygame.image.load("assets/firedash.ico")
    pygame.display.set_caption("pygame window")
    pygame.display.set_icon(icon)
    DISPLAY.fill(bg_color)
    pygame.display.update()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    y_velocity+=-5
        cube = pygame.draw.rect(DISPLAY,shape_color,(x,y,50,50))
        y+= y_velocity
        y_velocity+=acceleration
        if x_minus == None:
            x+=-2
        if x_minus == False:
            x+=2
        if x_minus == True:
            x+=-2
        if y > 800:
            y_velocity = -abs(y_velocity)
        if x < 0:
            x*=-1
            x_minus = False
        if x > 750:
            x*=-1
            x_minus = True
        pygame.time.delay(10)
        pygame.display.update()
        DISPLAY.fill(bg_color)
main()

Hi can someone tell me why my code isnt working well ? If i run it my cube will go to the left (which is what i want) and if it bump the left side it will bounce, and go to the right side but when it touches the right side the cube just disappear.. anyone has an idea on how to fix it ?

Asked By: qwatz

||

Answers:

You wrote:

if x > 750:
    x*=-1
    x_minus = True

So if x is for example 755 you will switch it to -755 and start moving to the left. Next loop it will be < 0 so you will switch it to +755 plus something and start moving to the right… and so on. It will be always out of bounds!

To debug these kinds of issues it helps to write your variables to the console: a print(f"pos {x},{y}") at the end of your loop will help you see what happens.

That said, what you probably want is something like this:

if x > 750:
    x = 750 - (x - 750) # (x - 750) is how far you have gone off screen
    x_minus = True
Answered By: rodrigo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.