logo
down
shadow

I can't move my player in pygame, can you figure why?


I can't move my player in pygame, can you figure why?

By : charlie campbell
Date : November 21 2020, 07:01 PM
hop of those help? I've restructured your main loop to fix the problems. I change the playerMovement (velocity) in the event loop now and use it to update the playerRect in the main loop with the pygame.Rect.move_ip method.
By the way, you can pass the playerRect to blit to blit the image at the topleft (x, y) coords.
code :
# The player's velocity. Define it outside of the main loop.
playerMovement = [0, 0]

while True:
    # Handle events.
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.type == pygame.K_RIGHT or event.key == pygame.K_d:
                playerMovement[0] = 2  # Set the x-velocity to the desired value.
            if event.type == pygame.K_LEFT or event.key == pygame.K_a:
                playerMovement[0] = -2
        if event.type == pygame.KEYUP:
            if event.type == pygame.K_RIGHT or event.key == pygame.K_d:
                playerMovement[0] = 0  # Stop the player when the button is released.
            if event.type == pygame.K_LEFT or event.key == pygame.K_a:
                playerMovement[0] = 0

    # Game logic.
    playerRect.move_ip(playerMovement)

    # Draw everything.
    display.fill((214, 42, 78))

    tileRect = []
    y = 0
    for row in level:
        x = 0
        for col in row:
            if col == '2':
                display.blit(grass, (x*16, y*16))
            if col == '1':
                display.blit(dirt, (x*16, y*16))
            if col != '0':
                tileRect.append(pygame.Rect(x*16,y*16,16,16))
            x += 1
        y += 1

    display.blit(player, playerRect)
    windowSurface.blit(pygame.transform.scale(display, windowSize), (0, 0))
    pygame.draw.rect(windowSurface, black, playerRect)
    pygame.display.update()
    mainClock.tick(60)


Share : facebook icon twitter icon
Cannot move player right on pygame

Cannot move player right on pygame


By : user2148587
Date : March 29 2020, 07:55 AM
I wish this helpful for you All of the fields stored in a pygame Rect are integers, but you are adding or substracting a fraction (0.5). My best guess is that when you subtract 0.5 from the x coordinate, it goes from (say) 112 to 111.5 and gets truncated to 111, so you move left one pixel. But if you add 0.5, it goes from 112 to 112.5 and gets truncated back to 112, so you don't move at all. I would suggest using whole numbers only.
How to make player move into next level in pygame

How to make player move into next level in pygame


By : Saravana
Date : March 29 2020, 07:55 AM
around this issue Firstly, some pieces of advice unrelated to your concrete question: Don't use enemy = ..., enemy2 = ..., enemy3 = ... and so on. Use lists
code :
self.enemies = [
  enemy(),
  enemy(),
  enemy()
]
    def hit_or_not(self):
        # Checking Collision of Enemy and Hero
        for enemy in self.enemies:
            self.enemyCollide(self.hero, enemy)
LEVELS = [
  {  # level1
    'enemies': [ 
      enemy(...),  # move here from your Game.__init__
      enemy(...),
      ....
    ],
    'platforms': [
      Platform(...),
      ...
    ]
    'coins': [
      Coins(...),
      ...
    'hero': thePlayer(...)
    ]
  }
  {  # level2
    ...
  }
  ...
] 
# in the Game class
def switchLevel(self, levelno):
   self.hero = LEVELS[levelno]['hero']
   self.enemies = LEVELS[levelno]['enemies']
   self.platforms = LEVELS[levelno]['platforms']
   self.coins = LEVELS[levelno]['coins']
game.switchLevel(...)
game.redrawGameWindow()
Pygame: Player won't move when key is held down

Pygame: Player won't move when key is held down


By : user3522770
Date : March 29 2020, 07:55 AM
Does that help You need to use pygame.key.get_pressed rather than the key down events. This way you know which keys are currently being pressed on every tick
code :
while True:
    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_RIGHT]:
        player.x += 5
    if pressed[pygame.K_DOWN]:
        player.y += 5
    if pressed[pygame.K_LEFT]:
        player.x -= 5
    if pressed[pygame.K_UP]:
        player.y -= 5
Why can only one player move at a time Pygame

Why can only one player move at a time Pygame


By : user3576598
Date : March 29 2020, 07:55 AM
it fixes the issue I think it would be better to separate the event from the class, so if you create a eventhandler class/function which calls the correct member function for the player will resolve this problem. As well the event consuming problem since only this event handler class has to be consume the events.
like :
code :
def Event_handler():
   if event.type == pygame.KEYDOWN:
       if event.key == ord("w"):
           player_1.up()                    
       elif event.key == ord("s"):
           player_1.down()
Pygame - Getting enemy sprites to move towards player

Pygame - Getting enemy sprites to move towards player


By : user3619141
Date : March 29 2020, 07:55 AM
To fix this issue I can't run code but I see two problems
1 - move_towards_player has to be inside class ZombieEnemy
code :
# --- classes ---

class ZombieEnemy(pygame.sprite.Sprite):

    def __init__(self, x=300, y=360):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('images/zombie.png')
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)

    def move_towards_player(self, player):
        # Find direction vector (dx, dy) between enemy and player.
        dx, dy = player.rect.x - self.rect.x, player.rect.y - self.rect.y
        dist = math.hypot (dx, dy)
        dx, dy = dx / dist, dy / dist # Normalize
        # Move along this normalized vector towards the player
        self.rect.x += dx * self.speed
        self.rect.y += dy * self.speed 

 # --- other ---

 all_zombies = pygame.sprite.Group()
    for zombie in all_zombies:
        zombie.move_towards_player(player)
while running:

    # --- events ---

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # If keystroke is pressed check right, left.
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            #playerX_change = -2.0
            BackGround.rect.left = BackGround.rect.left + 2.5
        if event.key == pygame.K_RIGHT:
            #playerX_change = 2.0
            BackGround.rect.left = BackGround.rect.left - 2.5
    # if event.type == pygame.KEYUP:
    #     if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
    #         BackGround.rect.left = 0

    # --- updates/moves ---

    playerX += playerX_change

    for zombie in all_zombies:
        zombie.move_towards_player(player)
    all_zombies.update()

    # --- draws ---

    screen.blit(BackGround.image, BackGround.rect)
    player(playerX,playerY)
    all_zombies.draw(screen)
    pygame.display.flip()
Related Posts Related Posts :
  • read a binary file (python)
  • Number Sequence in MySQL
  • Unit testing in python?
  • s/mime v3 with M2Crypto
  • Using wget via Python
  • Running a python script in background from a CGI
  • Edit Distance in Python
  • how to read url data
  • A RAM error of big array
  • Python: For loop problem
  • How do I create a list with 256 elements?
  • RAW Image processing in Python
  • access django session from a decorator
  • Multi-Threaded data insertion in MySQL using python
  • Making all variables accessible to namespace
  • What are the differences among sqlite3 from python2.5, pysqlite and apsw
  • Detect marker with opencv and python
  • Python ctypes and dynamic linking
  • Downloading a directory tree with ftplib
  • ImportError: No Module named simplejson
  • Pre-generating GUIDs for use in python?
  • `ipython` tab autocomplete does not work on imported module
  • Matching blank entries in django queryset for optional field with corresponding ones in a required field
  • Control VLC from Python in Windows
  • Return unicode string from python via ajax
  • Dynamically customize django admin columns?
  • Any way to add tabbed forms in django administration site?
  • Python / SQLite - database locked despite large timeouts
  • Encoding in XML declaration python
  • deletion of folders
  • Python Mindstorms RCX
  • Regex to split on successions of newline characters
  • Unicode filename to python subprocess.call()
  • Removing non-breaking spaces from strings using Python
  • Is there a way to backup everything in an app-engine blobstore?
  • Process a set of files from a source directory to a destination directory in Python
  • How to know if optparse option was passed in the command line or as a default
  • Rewriting a for loop in pure NumPy to decrease execution time
  • Comparing a time delta in python
  • Find next lower item in a sorted list
  • MySQLdb not INSERTING, _mysql does fine
  • Scipy Negative Distance? What?
  • What are the common patterns in web programming?
  • Percent signs in windows path
  • How to add a random number to a subsection of a numpy array?
  • How to generate all the values of an iterable besides the last few?
  • Searching by both class and range in XPath
  • Python code execution in Perl interpreter
  • Best Way to Include Variable in Python3
  • Serialize the @property methods in a Python class
  • What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
  • Good way to edit the previous defined class in ipython
  • Bounced email on Google App Engine
  • Search jpeg files using python
  • Dynamically create class attributes
  • python unichr problem
  • Python beginner, strange output problem
  • Python: Finding a value in 1 list and finding that corresponding index in another list
  • can't install mysqlclient on mac os x mojave
  • Error indicates flattened dimensions when loading pre-trained network
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk