在使用此脚本进行简单的矢量数学运算时,我可以在值为整数(例如 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()