I have created this to move a sprite. I set a sprite images cordinates to (spritex, 300) in a diffrent file. When run the program and press the right or left arrow, there is no movement. The value of spritex changes, in a print function
I have checked that the program is reading the key press’s by adding a print function. Am I setting up the program wrong?
——Movement Function File
import pygame
import os, sys
from itertools import *
from oryxsprites import *
from oryxdisplay import *
spritex = 300
screen = pygame.display.set_mode((640, 640))
def movementsprite():
global spritex
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if keys[pygame.K_RIGHT]:
spritex += 10
print spritex
elif keys[pygame.K_LEFT]:
spritex -= 10
print spritex
——Display Function file—————
import pygame
import itertools
from oryxsprites import *
from McharMovement import *
screen = pygame.display.set_mode((640, 640))
spritex = 300
def backgroundmain():
movementsprite()
backdrop = pygame.Rect(0, 0, 640, 640)
screen.fill((50,50,50))
playingfeildwidth = (32, 608)
playingfeildheight = (32, 608)
screen.blit(warrior1, (spritex, 320))
pygame.display.flip()
——–Main File——————
import pygame
import os, sys
from itertools import *
from oryxsprites import *
from oryxdisplay import *
from McharMovement import *
running = True
while running:
backgroundmain()
pygame.display.set_caption('OryxGame')
pygame.display.set_icon(grasstile)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
Change your code to:
That should work fine
If the sprite is still not moving, then the problem is now when you call your function to move it. How are you moving it? You need to call that movement function from inside
def movementsprite():And if you want to call the movement function from another file, use
from other_file import movement_funcor even
from other_file import *UPDATE:
Just add a return statement to your movement function,
return spritexThen in the Display function, when you call the movement function change the line to
spritex=movementfunction()That will alter the value of spritex between the files. And you dont have to make spritex global at the top of your movement function.
Hope I could help! 🙂