Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

python - My enemies stop moving if i move my player


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The result of ene_x // dist and ene_y // dist is always 0. To calculate the movement, you must use the / (division) operator rather than the // (floor division) operator

ene_x, ene_y = ene_x // dist, ene_y // dist

ene_x, ene_y = ene_x / dist, ene_y / dist

Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.

The coordinates for Rect objects are all integers. [...]

The fraction part of the movement gets lost when the position of the object incremented:

self.enemy_rect.x += ene_x * self.ENEMY_ACCELERATION
self.enemy_rect.y += ene_y * self.ENEMY_ACCELERATION

If you want to store object positions with floating point accuracy, you have to store the location of the object in separate variables respectively attributes and to synchronize the pygame.Rect object. round the coordinates and assign it to the location (e.g. .topleft) of the rectangle:

x, y = # floating point coordinates
rect.topleft = round(x), round(y)

Add floating point coordinates to the Enemy class:

class Enemy:

    def __init__(self, enemy_y, enemy_x):
        # [...]

        self.enemy_rect = pygame.Rect(enemy_x, enemy_y, self.ENEMY_HEIGHT, self.ENEMY_WIDTH)
        self.x, self.y = self.enemy_rect.topleft

        # [...]
        

    def enemyMovement(self, player_x, player_y):
        ene_x, ene_y = player_x - self.x, player_y - self.y
        dist = math.hypot(ene_x, ene_y)
        ene_x, ene_y = ene_x / dist, ene_y / dist

        self.x += ene_x * self.ENEMY_ACCELERATION
        self.y += ene_y * self.ENEMY_ACCELERATION
        self.enemy_rect = round(self.x), round(self.y)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...