0

I have the code to move 2 objects across my screen. What I want them to do is reach the other side, and restart back at the beginning, however they just cross the screen and disappear.

import pygame, sys, time, random
from pygame.locals import *
pygame.init()
winW = 500
winH = 300
surface = pygame.display.set_mode ((winW, winH),0,32)

class Enemy():
    def __init__(self, char, xMoveAmnt, startY=0, startX=0):
        self.char = char
        self.x = startX
        self.y = startY
        self.startX=startX
        self.startY=startY
        self.xMoveAmnt = xMoveAmnt
        self.image = pygame.image.load(self.char)
        self.rect = self.image.get_rect()


    def moveChar(self):
        self.x += self.xMoveAmnt
        if self.rect.right >= 500:
            self.x=self.startX

enemyList = []
for i in range (0, 2):

    leftOrRight1 = random.randint(0,1)
    if leftOrRight1 == 0:
         leftOrRight = 0
         xMoveAmnt = 20
    elif leftOrRight1 == 1:
        leftOrRight = 500
        xMoveAmnt = -20
    enemyList.append(Enemy(("orc.png"), xMoveAmnt, random.randint(0, 300), leftOrRight))

while True:
    surface.fill ((255,255,255))
    for enemy in enemyList:
        enemy.moveChar()
        surface.blit(enemy.image, (enemy.x, enemy.y))
        time.sleep(00.04)        
    pygame.display.update()

What could be causing this?

2
  • What determines the position of an Enemy? Is it x: self.x +=... or is it rect: if self.rect.right >=... Commented Jun 18, 2013 at 23:38
  • self.x is the x of the object. Increasing it moves the object, the if is meant to move the object back to the starting position when it reaches the far side. Commented Jun 18, 2013 at 23:44

2 Answers 2

1
    self.x += self.xMoveAmnt

Here, you increase the x of the Enemy to move it.

    if self.rect.right >= 500:

You were increasing x but now you are checking rect.right. If you are increasing x rect.right will not increase. Maybe you meant to do this:

    if self.x + self.rect.right >= 500:

?

Sign up to request clarification or add additional context in comments.

1 Comment

rect.right is a property, it's equivalent to rect.x + rect.width
0

The problem here is that your doing a test on the position of the image's bounding rectangle ( if self.rect.right >= 500) while this rectangle is not updated (as you use a 'custom' variable, x, for the image's position).

Try doing something like that:

def moveChar(self):
    self.x += self.xMoveAmnt
    if self.x >= 500:
        self.x = self.startX

You could also use the modulo operator for that kind of things:

def moveChar(self):
    self.x = (self.x + self.xMoveAmnt) % 500

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.