Bottom Page

Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 [PyGame] How to stop the sprite's movement when it touches the edges of the screen?
#1
I created my first sprite with Pygame and managed to make it move with keyboard keys. However, when it encounters the edges of the screen, it keeps moving beyond them, disappearing from the screen. I would like to make it stop when it touches the edges, how can I do it?

This is my code: https://imgur.com/8N3hUTg
Quote
#2
Hi

I don't know how to solve your problem, however, it would make it easier for someone to help you if you used " insert python code" .

you can read about it above you post " please make sure to use python tags when inserting code into the forum"

example
"""this is stuff"""
import numpy as np 
data=np.zero((5,5))
....
When it is formatted like this it so much easier to work with. Just copy and paste. This way we can play around with your code and see if we can get it to work. However, I am lazy, so I don't want to manually write it into my editor :P

BR Mark
metulburr likes this post
Quote
#3
(May-12-2018, 10:56 AM)Mark3232 Wrote: Hi

I don't know how to solve your problem, however, it would make it easier for someone to help you if you used " insert python code" .

you can read about it above you post " please make sure to use python tags when inserting code into the forum"

example
"""this is stuff"""
import numpy as np 
data=np.zero((5,5))
....
When it is formatted like this it so much easier to work with. Just copy and paste. This way we can play around with your code and see if we can get it to work. However, I am lazy, so I don't want to manually write it into my editor :P

BR Mark


Ok. Here's the code:

import pygame
from pygame import *
import sys

WIDTH = 600
HEIGHT = 480
FPS = 60

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

class Player(pygame.sprite.Sprite):
    # sprite for the player
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)

# initialize pygame and create window
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My game")
clock = pygame.time.Clock()
pygame.key.set_repeat(True)

all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

# Game loop
while True:
    # keep loop running at the right speed
    clock.tick(FPS)
    # Process input (events)
    for event in pygame.event.get():
        # check for closing window
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # Moving sprites with arrow keys or WASD
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP or event.key == K_w:
                player.rect.centery -= 5
            elif event.key == pygame.K_DOWN or event.key == K_s:
                player.rect.centery += 5
            elif event.key == pygame.K_LEFT or event.key == K_a:
                player.rect.left -= 5
            elif event.key == pygame.K_RIGHT or event.key == K_d:
                player.rect.right += 5

    # Update
    all_sprites.update()

    # Draw / render
    screen.fill(BLACK)
    all_sprites.draw(screen)
    # *after* drawing everything, flip the display
    pygame.display.flip()
Quote
#4
the simple method would be to clamp it in place of the entire screen.

In your player class if you add an update method and in it
self.rect.clamp_ip(screen.get_rect())
where self.rect is the rect of the player and screen.get_rect() is the screen from display and returns a rect of the screen size. But obviously you would want to pre determine the screen size and set it to that, not do it every frame.

and example would be here of similar task
https://python-forum.io/Thread-PyGame-Ba...ing-part-3
The 5th code box from the top
Mekire likes this post
Quote
#5
I'd do it this way, check if player's sprite x axis position + player's sprite width is lower than screen width, if it is, then move sprite to the right.
Example in your code:

import pygame
from pygame import *
import sys
 
WIDTH = 600
HEIGHT = 480
FPS = 60
 
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
 
class Player(pygame.sprite.Sprite):
    # sprite for the player
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)
 
# initialize pygame and create window
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My game")
clock = pygame.time.Clock()
pygame.key.set_repeat(True)
 
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
 
# Game loop
while True:
    # keep loop running at the right speed
    clock.tick(FPS)
    # Process input (events)
    for event in pygame.event.get():
        # check for closing window
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # Moving sprites with arrow keys or WASD
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP or event.key == K_w:
                player.rect.centery -= 5
            elif event.key == pygame.K_DOWN or event.key == K_s:
                player.rect.centery += 5
            elif event.key == pygame.K_LEFT or event.key == K_a:
                player.rect.left -= 5
            elif event.key == pygame.K_RIGHT or event.key == K_d:
                # basically, if (sprite.x + sprite.width < screen.width): sprite.x += 5
                if player.rect.x + player.imange.get_width() < WIDTH:
                    # not sure if methods are correct
                    player.rect.right += 5
 
    # Update
    all_sprites.update()
 
    # Draw / render
    screen.fill(BLACK)
    all_sprites.draw(screen)
    # *after* drawing everything, flip the display
    pygame.display.flip()
Quote
#6
(May-13-2018, 03:31 PM)Raures Wrote: I'd do it this way, check if player's sprite x axis position + player's sprite width is lower than screen width, if it is, then move sprite to the right.
Example in your code:

import pygame
from pygame import *
import sys
 
WIDTH = 600
HEIGHT = 480
FPS = 60
 
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
 
class Player(pygame.sprite.Sprite):
    # sprite for the player
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)
 
# initialize pygame and create window
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My game")
clock = pygame.time.Clock()
pygame.key.set_repeat(True)
 
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
 
# Game loop
while True:
    # keep loop running at the right speed
    clock.tick(FPS)
    # Process input (events)
    for event in pygame.event.get():
        # check for closing window
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # Moving sprites with arrow keys or WASD
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP or event.key == K_w:
                player.rect.centery -= 5
            elif event.key == pygame.K_DOWN or event.key == K_s:
                player.rect.centery += 5
            elif event.key == pygame.K_LEFT or event.key == K_a:
                player.rect.left -= 5
            elif event.key == pygame.K_RIGHT or event.key == K_d:
                # basically, if (sprite.x + sprite.width < screen.width): sprite.x += 5
                if player.rect.x + player.imange.get_width() < WIDTH:
                    # not sure if methods are correct
                    player.rect.right += 5
 
    # Update
    all_sprites.update()
 
    # Draw / render
    screen.fill(BLACK)
    all_sprites.draw(screen)
    # *after* drawing everything, flip the display
    pygame.display.flip()

I tried it, but this way the sprite only moves upward-right, stops only at the right edge and refuses to move leftward
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Using classes for room movement (text game) Lawr3y 3 288 Aug-20-2019, 12:40 AM
Last Post: Lawr3y
  [PyGame] How to create a sprite in a different module I_like_pepperjack 1 249 Aug-15-2019, 10:23 AM
Last Post: metulburr
  Need help making a sprite GalaxyCoyote 4 293 Aug-11-2019, 09:12 PM
Last Post: metulburr
  Problem with coding for movement keys Aresofthesea 3 321 Jul-05-2019, 07:05 PM
Last Post: nilamo
  creating sprite mask pfaber11 5 486 Jun-12-2019, 09:39 PM
Last Post: pfaber11
  [PyGame] pygame.draw.rect function stretches across the screen instead of moving BubblesTheGiraffe 2 411 Jun-11-2019, 08:32 PM
Last Post: metulburr
  [PyGame] Making Player Sprite Ricochet of walls michael1789 4 386 Jun-03-2019, 10:45 PM
Last Post: Windspar
  [PyGame] assigning rect to sprite pfaber11 1 257 May-18-2019, 05:39 PM
Last Post: metulburr
  moving a sprite pfaber11 3 476 May-15-2019, 12:52 PM
Last Post: pfaber11
  Pygame Movement X/Y coord TheHumbleIdiot 2 392 Mar-19-2019, 02:21 PM
Last Post: TheHumbleIdiot

Forum Jump:


Users browsing this thread: 1 Guest(s)