gpt4 book ai didi

python - Pygame 形状不能采用非整数参数

转载 作者:行者123 更新时间:2023-12-04 17:48:35 25 4
gpt4 key购买 nike

在 Pygame 模块中,形状不能将浮点值作为参数是否重要?

之所以提出这个问题,是因为我目前正在做一个相对基础的物理模拟,并使用 pygame 来做图形,在物理模拟中,很少/从来没有发生过一个对象居中,以至于它有一个整数值。

我主要想知道这是否会对模拟的准确性产生重大影响?

最佳答案

我通常建议将游戏对象的位置和速度存储为 vectors (其中包含 float )以保持物理准确。然后,您可以先将速度添加到位置向量,然后更新对象的矩形作为 blit 位置,可用于碰撞检测。在将其分配给矩形之前,您不必将位置向量转换为整数,因为 pygame 会自动为您完成。

这是一个对象跟随鼠标的小例子。

import pygame as pg
from pygame.math import Vector2


class Player(pg.sprite.Sprite):

def __init__(self, pos, *groups):
super().__init__(*groups)
self.image = pg.Surface((30, 30))
self.image.fill(pg.Color('steelblue2'))
self.rect = self.image.get_rect(center=pos)
self.direction = Vector2(1, 0)
self.pos = Vector2(pos)

def update(self):
radius, angle = (pg.mouse.get_pos() - self.pos).as_polar()
self.velocity = self.direction.rotate(angle) * 3
# Add the velocity to the pos vector and then update the
# rect to move the sprite.
self.pos += self.velocity
self.rect.center = self.pos


def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
font = pg.font.Font(None, 30)
color = pg.Color('steelblue2')
all_sprites = pg.sprite.Group()
player = Player((100, 300), all_sprites)

done = False

while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True

all_sprites.update()
screen.fill((30, 30, 30))
all_sprites.draw(screen)
txt = font.render(str(player.pos), True, color)
screen.blit(txt, (30, 30))

pg.display.flip()
clock.tick(30)


if __name__ == '__main__':
pg.init()
main()
pg.quit()

关于python - Pygame 形状不能采用非整数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46991803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com