Неожиданное поведение внутри простой функции, не могу найти почему - PullRequest
0 голосов
/ 23 января 2019

Я пытаюсь написать простую игру, используя Pygame Lib.Я запрограммировал очень простое поведение « врага », чтобы следовать за игроком.

Проблема возникает, когда я запускаю игру и объект « враг »движется быстрее, когда идет в правильном направлении, и медленнее, когда идет влево.

Я уже искал любое неверное число или оператор, которые могут повлиять на функцию.Также я отслеживал значение скорости и времени (которое я использую, чтобы добавить или выделить « distance »), и они не меняются (они не должны изменяться).

import os
import sys
import pygame as py
from pygame.locals import *

# Constantes
w = 500
h = 300
clock = py.time.Clock()

active_surf = py.Surface((500, 30))
active_surf.fill((255, 255, 0))

ground_surf = py.Surface((500, 50))
ground_surf.fill((127, 127, 127))

# Clases


class Robbie(py.sprite.Sprite):
    def __init__(self, ):
        py.sprite.Sprite.__init__(self)
        self.image = py.Surface((30, 30))
        self.rect = self.image.get_rect()
        self.rect.bottom = 250
        self.rect.centerx = 230
        self.speed = 0.2

    def move(self, keys, time):
        if self.rect.left >= 0:
            if keys[K_LEFT]:
                self.rect.centerx -= self.speed * time
        if self.rect.right <= w:
            if keys[K_RIGHT]:
                self.rect.centerx += self.speed * time

    def shoot(self, keys, time):
        pass


class Enemy(py.sprite.Sprite):
    def __init__(self):
        py.sprite.Sprite.__init__(self)
        self.image = py.Surface((25, 25))
        self.rect = self.image.get_rect()
        self.rect.bottom = 250
        self.rect.centerx = 260
        self.speed = 0.1

    def move(self, player, time):
        if player.rect.centerx > self.rect.centerx:
            self.rect.centerx += self.speed * time
        if player.rect.centerx < self.rect.centerx:
            self.rect.centerx -= self.speed * time

# Funciones
def img_load(img_name):
    img_path = os.path.join((os.path.dirname(__file__)), "Images", (img_name + ".png"))
    sprite_obj = py.image.load(img_path).convert_alpha()
    return sprite_obj


def main():
    screen = py.display.set_mode((w, h))
    py.display.set_caption("RobbiShoot")
    screen.blit(ground_surf, (0, 250))
    player = Robbie()
    enemy = Enemy()

    while True:
        time = clock.tick(60)
        keys = py.key.get_pressed()

        for events in py.event.get():
            if events.type == QUIT:
                sys.exit()

        screen.blit(active_surf, (0, 220))
        player.move(keys, time)
        enemy.move(player, time)
        screen.blit(player.image, player.rect)
        screen.blit(enemy.image, enemy.rect)
        py.display.flip()
    return 0


if __name__ == '__main__':
    py.init()
    main()

Я думал, что это может быть простая математическая вещь, но если это так, я не вижу этого.

1 Ответ

0 голосов
/ 23 января 2019

Это проблема приведения значения с плавающей запятой к целочисленным значениям:

def move(self, player, time):
    if player.rect.centerx > self.rect.centerx:
        self.rect.centerx = (self.rect.centerx + self.speed * time + 0.5)
    if player.rect.centerx < self.rect.centerx:
        self.rect.centerx = (self.rect.centerx - self.speed * time + 0.5)

или

def move(self, player, time):
    if player.rect.centerx > self.rect.centerx:
        self.rect.centerx = round(self.rect.centerx + self.speed * time)
    if player.rect.centerx < self.rect.centerx:
        self.rect.centerx = round(self.rect.centerx - self.speed * time)

Обратите внимание: если вы преобразуете 0,1 в целое значение, чем 0, но если вы преобразуете 0,9, это тоже 0. Результат с плавающей точкой вычисления координаты x должен быть округлен до 0,5.
В коде ответа координата x всегда усекается, поэтому позиция стремится влево.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...