0

在使用此脚本进行简单的矢量数学运算时,我可以在值为整数(例如 1 和 2)时添加速度矢量,但是当速度矢量用浮点数 0.5 初始化时没有运动。据我所知,python 不需要声明 float 或 int,但我感觉结果数字被截断

import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800, 600))
background = pygame.Surface(screen.get_size())

rectangle = pygame.Rect(65, 45, 50, 50)

class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __iadd__(self, vector):
        self.x += vector.x
        self.y += vector.y
        return self

    def __isub__(self, vector):
        self.x -= vector.x
        self.y -= vector.y
        return self

    def copy(self, vector):
        self.x = vector.x
        self.y = vector.y

speed = Vector2D(.5, .5)
going = True

while going:
#Handle Input Events
    for event in pygame.event.get():
        if event.type == QUIT:
            going = False
        elif event.type == KEYDOWN and event.key == K_ESCAPE:
            going = False


    rectangle.left += speed.x
    rectangle.top += speed.y

    #Draw Everything
    screen.blit(background, (0, 0))
    pygame.draw.rect(screen, (255, 255, 255), rectangle, 1)
    pygame.display.flip()

pygame.quit()
4

1 回答 1

2

由于没有半个像素Rect类的东西,因此该类会截断您要添加的浮点数的小数。

因此,跟踪Vector2D班级内的位置是一个更好的主意:

class Vector2D:
    def __init__(self, x, y, vx, vy):
        self.x = x
        self.y = y
        self.vx = vx
        self.vy = vy

    def update(self):
        self.x += self.vx
        self.y += self.vy

    def copyto(self, rect):
        rect.x = int(round(self.x,0)) 
        rect.y = int(round(self.y,0))


speed = Vector2D(100, 100, .5, .5)

并有这个:

speed.update()
speed.copyto(rectangle)

代替:

rectangle.left += speed.x
rectangle.top += speed.y
于 2013-04-28T05:13:05.937 回答