0

このスクリプトを単純なベクトル計算に使用すると、値が 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()
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 に答える