Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PYGAME中的移动对象_Python_Oop_Object_Pygame - Fatal编程技术网

Python PYGAME中的移动对象

Python PYGAME中的移动对象,python,oop,object,pygame,Python,Oop,Object,Pygame,我有代码在屏幕上移动两个对象。我想让他们做的是到达另一边,然后重新开始,然而他们只是穿过屏幕消失 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, xMove

我有代码在屏幕上移动两个对象。我想让他们做的是到达另一边,然后重新开始,然而他们只是穿过屏幕消失

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()

这可能是什么原因造成的?

这里的问题是,您正在对图像的边界矩形的位置进行测试(
如果self.rect.right>=500
),而该矩形没有更新(因为您使用了一个“自定义”变量,
x
,用于图像的位置)

尝试这样做:

def moveChar(self):
    self.x += self.xMoveAmnt
    if self.x >= 500:
        self.x = self.startX
你也可以用模运算符来处理这类事情:

def moveChar(self):
    self.x = (self.x + self.xMoveAmnt) % 500
在这里,你增加敌人的
x
来移动它

    if self.rect.right >= 500:
您正在增加
x
,但现在正在检查
rect.right
。如果您正在增加
x
rect.right
将不会增加。也许你本想这么做:

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

什么决定了敌人的位置?它是x:
self.x+=…
还是rect:
如果self.rect.right>=…
self.x是对象的x。增加它将移动对象,if意味着在对象到达远端时将对象移回起始位置。
rect.right
是一个属性,它相当于
rect.x+rect.width
    if self.x + self.rect.right >= 500: