Greeting, I trying to set the boundaries for players in a game so they do not go passed the boundaries of the screen. They only move in the x-axis.
Bellow is the code for the player class. Right now In the move method I am trying to set a distance relative to the rectangle object(the player) do that it does not go past a certain points to the left and right of the x-axis. However, right now I keep getting the error
if self.rect.left + dx < 0: AttributeError: 'tuple' object has no attribute 'left'
when I run the code.
class Player():
def __init__(self, x, y, width, height, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.rect = pygame.Rect((x,y, width, height))
def move(self, screen_width, screen_height):
SPEED = 10
dx = 0
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.x -= SPEED
dx = -SPEED
if keys[pygame.K_RIGHT]:
self.x += SPEED
dx = SPEED
# ensure player stays on screen
if self.rect.left + dx < 0:
self.rect.x += -self.rect.left
if self.rect.right + dx > screen_width:
self.rect.x += screen_width - self.rect.right
self.update()
def update(self):
# update player position
self.rect = (self.x, self.y, self.width, self.height)