Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 ?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading