在使用此脚本进行简单向量数学运算时,我可以在值为1和2之类的整数时添加速度向量,但是当使用float .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()
答案 0 :(得分: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