【问题标题】:Pygame smooth movementPygame 平滑运动
【发布时间】:2020-02-29 00:47:47
【问题描述】:

如何让 pygame rect 顺利移动?就像我将 x 位置更新 2 一样,它看起来很平滑,但如果我用更大的数字(例如 25)更新它,它就会传送到该位置。另外,如果可能的话,这也适用于小数吗?

Visual Representation

import pygame
import math

GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)

class Dot(pygame.sprite.Sprite):
    # This class represents a car. It derives from the "Sprite" class in Pygame.
    def __init__(self, color, width, height):

        # Call the parent class (Sprite) constructor
        super().__init__()

        # Pass in the color of the car, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)
        self.color = color
        self.width = width
        self.height = height
        pygame.draw.rect(self.image, self.color, [0, 0, self.width, self.height])
        self.rect = self.image.get_rect()

【问题讨论】:

  • 尝试将距离减半,将clock.tick时间戳加倍
  • 为什么要在构造函数中绘制一个矩形(pygame.draw.rect)?这似乎没有任何意义。

标签: pygame smoothing


【解决方案1】:

如何让 pygame rect 顺利移动?

如果您的矩形必须每帧移动 25 像素,那么在两者之间的位置绘制矩形是没有意义的。显示每帧更新一次,在两者之间的位置绘制矩形完全没有意义。
可能你必须减少每秒的帧数。在这种情况下,您必须增加帧速率并且可以减少移动。请注意,人眼每秒只能处理一定数量的图像。诀窍是生成足够多的帧,使人眼的运动看起来很流畅。

pygame.Rect 只能存储整数值。如果要以非常高的帧率和浮点精度进行操作,则必须将对象的位置存储在单独的浮点属性中。将圆角位置与矩形属性同步。请注意,您不能在窗口的“一半”像素上绘图(至少在 pygame 中)。

例如:

class Dot(pygame.sprite.Sprite):
    # This class represents a car. It derives from the "Sprite" class in Pygame.
    def __init__(self, color, x, y, width, height):

        # Call the parent class (Sprite) constructor
        super().__init__()

        # Pass in the color of the car, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.x = x
        self.y = y
        self.image = pygame.Surface([width, height])
        self.image.fill(self.color)
        self.rect = self.image.get_rect(center = (round(x), round(y)))

    def update(self):
        # update position of object (change `self.x`,  ``self.y``)
        # [...]

        # synchronize position to `.rect`
        self.rect.center = (round(x), round(y))

【讨论】:

    猜你喜欢
    • 2016-09-25
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2018-09-30
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    相关资源
    最近更新 更多