0

Here I have 2 classes; Player and Obstacle. Player has some basic movement with input from keys. I change Player.rect.x to change the position of player. In Obstacle I have a code that detects if the Player.rect.x reaches the same x postion as Obstacle.rect.x, if so print "test".

Code:

import pygame

pygame.init()

class Player(pygame.sprite.Sprite):
    def __init__(self):
        #initializing code

    def movement(self):
        #code for movement

    def update(self):
        self.movement()

class Obstacle(pygame.sprite.Sprite):
    def __init__(self):
        #intitializing code

    def test(self):
        player_char = Player() 
        if self.rect.x == player_char.rect.x :
            print("test")

    def update(self):
        self.test()

I used print statements to figure out that player_char.rect.x changes in the Player class but not in the Obstacle class. Hence player_char.rect.x stays the same as it was when we did move it. player_char.rect.x simply doesn't update so the if statement will never become true. How can I update player_char.rect.x in Obstacle class also?

I am pretty new to python so this might turn out to be a stupid mistake.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 1
    It's hard to tell what your question is. If you want to compare a `Player` object with an `Obstacle` you can overide `__eq__` for example. – Fiddling Bits Aug 19 '23 at 21:45
  • `player_char = Player()` creates a completely new `player` object and does not refer to an existing one. If you want to detect the collision of objects, see [How do I detect collision in pygame?](https://stackoverflow.com/questions/29640685/how-do-i-detect-collision-in-pygame) – Rabbid76 Aug 20 '23 at 05:32
  • Your `test` doesn't look at an existing player. It creates a BRAND NEW character, and then compares the location. You would need to pass the player you want to check into `Obstacle.test` so it can fetch the location. I assume you have a global player object, or maybe a list of players. – Tim Roberts Aug 20 '23 at 05:40

0 Answers0