0

I am making a game right now and I want the cat character to move more smoothly instead of in random bursts. I also want the background to move based on where the character is instead of on its own. For example, if the character moves past a certain point to the right, the background will move to accommodate this. If not, the background will stay still.

import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d, %d" %(20, 20)
from pygame import * 
init()
size = width, height = 1000, 600
screen = display.set_mode(size)
button = 0
myFont = font.SysFont("Times New Roman",30)

PRESS_RIGHT = False
PRESS_LEFT = False
PRESS_UP = False
PRESS_DOWN = False

dung = image.load("dung.jpg")
dung = transform.scale(dung, (width, height))
cat = image.load("catchar.png")
cat = transform.scale(cat,(200,200))
cat = transform.flip(cat,(True),False)

#Icon
display.set_icon(cat)





def drawScene(backx):
    screen.blit(dung, Rect(backx,0,width,height))    #draw the picture
    screen.blit(dung, Rect(backx + width, 0, width, height))

def cats(spritex):
    screen.blit(cat, (spritex,315))

running = True
myClock = time.Clock()
backgroundX = 0
catx = 200
# Game Loop
while running:

    # Caption
    display.set_caption("Joey's Adventure " + str(mouse.get_pos()[0]) + ", " + str(mouse.get_pos()[1]))

    for e in event.get():             # checks all events that happen
        if e.type == QUIT:
            running =False
        elif e.type == KEYDOWN:
            if e.key == K_RIGHT:
                PRESS_RIGHT = True
                print ("right")
            if e.key == K_LEFT:
                PRESS_LEFT = True 
                print ("left")
            if e.key == K_UP:
                PRESS_UP = True

        keys_pressed = key.get_pressed()

        if keys_pressed[K_LEFT]:
            catx -= 5

        if keys_pressed[K_RIGHT]:
            catx += 5    


    drawScene(backgroundX)
    cats(catx)
    myClock.tick(60)                     # waits long enough to have 60 fps
    backgroundX -= 1
    if backgroundX < -1*width:
        backgroundX = 0
    display.flip()

quit()
Rabbid76
  • 177,135
  • 25
  • 101
  • 146
conyieie
  • 213
  • 1
  • 7
  • You seem to change the position immediately when you process the event, as opposed to having concepts of velocity/acceleration, or even some kind of buffer to be drained. This can lead to the "jerky" behavior you see. Perhaps if you move the `keys_pressed` logic outside the event loop and use your `PRESS_...` variables this would help? – Cireo Jun 03 '20 at 21:11
  • @Cireo it didnt work outside of the event loop. – conyieie Jun 03 '20 at 22:34
  • 1
    Try looking at https://stackoverflow.com/questions/16044229/how-to-get-keyboard-input-in-pygame – Cireo Jun 03 '20 at 22:51

0 Answers0