2

所以我决定在 pygame 中为我的矩形字符添加线性插值。几天前我看到了 lerp,我不确定我是否遗漏了什么。

问题是:例如当我向右移动时。速度插值以达到所需的最大速度 - (7) 或(左侧为 -7)。当我释放键时,速度再次插入,从最大速度到 0,非常平滑。但是,如果我在向右移动时按下左键,则插值从速度 7 变为 0,使我的角色停止。

编辑:这是整个游戏的一部分,我跳过了跳跃和窗口边界碰撞检测等功能。但是这段代码仍然重现了我不想要的动作。

import pygame
import sys
import math
import datetime
from pygame.locals import *

class Vector(object):
    ''' Performs vector aritmetics
    '''
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def add(self, v):
        x = self.x + v.x
        y = self.y + v.y
        return Vector(x, y)

class GroundData(object):
    ''' Ground data structure.
    Creates a ground data structure and her component's.
    '''
    def __init__(self):
        # Vectors
        self.position = Vector(0, WINDOWHEIGHT - WINDOWHEIGHT / 3)
        self.size = Vector(WINDOWWIDTH, WINDOWHEIGHT-self.position.y)

        # Ground data structure
        self.color = (128, 128, 128) # Gray
        self.rect = pygame.Rect((self.position.x, self.position.y),
                             (self.size.x, self.size.y))
        self.ground = {'shape': self.rect, 'color': self.color}

    def draw(self):
        ''' Draw's the ground shape and color using pygame.draw.rect(...).
        '''
        pygame.draw.rect(WINDOWSURFACE, self.ground['color'],
                                    self.ground['shape'])


class PlayerData(object):
    ''' Player data structure.
    Creates a player data structure and handles few actions.
    '''
    def __init__(self):
        self.ground = GroundData()

        # Vectors
        self.size = Vector(50, 70)
        self.position = Vector(
            15, self.ground.position.y - self.size.y + 1) # + 1 forced collision
        self.velocity = Vector(0, 0)
        self.velocity_goal = Vector(0, 0)
        self.gravity = Vector(0, 3)

        # Player data structure
        self.color = (0, 100, 0) # Dark Green
        self.rect = pygame.Rect((self.position.x, self.position.y),
                                (self.size.x, self.size.y))
        self.player = {'shape': self.rect, 'color': self.color}

    def is_colliding_ground(self):
        ''' Returns true if player shape is colliding with a ground.
        '''
        if self.position.y + self.size.y >= self.ground.position.y:
            return True
        return False

    def approach(self, vel_goal, vel_curr, dt):
        difference = vel_goal - vel_curr
        if difference > dt:
            return vel_curr + dt
        if difference < -dt:
            return vel_curr - dt
        return vel_goal

    def update(self, dt):
        self.velocity.x = self.approach(self.velocity_goal.x,
                                    self.velocity.x, dt * 95)
        # Update position and velocity
        # self.position = self.position.add(self.velocity) * dt
        # If I mult (x, y) by dt I get alot slower.
        self.position = self.position.add(self.velocity)
        self.player['shape'].top = self.position.y
        self.player['shape'].left = self.position.x

    def draw(self):
        ''' Draw's the player shape and color using pygame.draw.rect(...).
        '''
        pygame.draw.rect(WINDOWSURFACE, self.player['color'],
                                    self.player['shape'])


class EventManagement(object):
    ''' Handles keyboard event's.
    Toggles player variables according to the event's.
    '''
    def __init__(self, player):
        self.player = player

    def is_doneloop(self, flag):
        global is_doneloop
        is_doneloop = flag
        return is_doneloop

    def listen(self):
        ''' Toggles player variables according to keyboard/mouse input.
        '''
        for event in pygame.event.get():
            if event.type == QUIT:
                self.is_doneloop(True)

            if event.type == KEYDOWN:
                if event.key == ord('a'):
                    self.player.velocity_goal.x = -7
                if event.key == ord('d'):
                    self.player.velocity_goal.x = 7

            if event.type == KEYUP:
                if event.key == K_ESCAPE:
                    self.is_doneloop(True)
                if event.key == ord('a'):
                    self.player.velocity_goal.x = 0
                if event.key == ord('d'):
                    self.player.velocity_goal.x = 0

#-------------------------------------------------------------------------

WINDOWWIDTH = 900
WINDOWHEIGHT = 500
WINDOWSURFACE = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
is_doneloop = False
Clock = pygame.time.Clock()
FPS = 40

def mainloop():
    pygame.init()
    Ground = GroundData()
    Player = PlayerData()
    EventHandle = EventManagement(Player)

    prev_time = 0
    curr_time = datetime.datetime.now()

    while not is_doneloop:
        # Get deltaT
        dt = Clock.tick(FPS)
        dt = dt / 1000.0 # Convert milliseconds to seconds
        pygame.display.set_caption('FPS: %.2f' % Clock.get_fps())

        # Handle events
        EventHandle.listen()

        # Update game state
        Player.update(dt)

        # Draw
        WINDOWSURFACE.fill((0, 0, 0)) # Black
        Ground.draw()
        Player.draw()
        pygame.display.update()

    pygame.quit()
    sys.exit()

if __name__ == '__main__':
    mainloop()

我的活动课上的更新 2

class EventManager(object):
''' Event management.
Listens and handles keyboard and mouse events.
'''
def __init__(self, player):
    self.player = player

    # Player movement flags, according to keyboard/mouse state
    self.is_move_left, self.is_move_right = False, False
    self.is_jump = False

def exit_game(self):
    ''' Closes pygame and sys modules.
    A break statement follows this method to break the mainloop.
    '''
    pygame.quit()
    sys.exit()

def listener(self):
    ''' Toggles Player movement flags, according to keyboard/mouse state.
    '''
    for event in pygame.event.get():
        if event.type == QUIT:
            self.exit_game()
            break

        if event.type == KEYDOWN:
            if event.key == K_a:
                self.is_move_left = True
            elif event.key == K_d:
                self.is_move_right = True

        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                self.exit_game()
                break
            if event.key == K_a:
                self.is_move_left = False
            elif event.key == K_d:
               self.is_move_right = False

def handler(self):
    ''' Set Player velocity_goal according to movement flags.
    '''
    if self.is_move_left and not self.is_move_right:
        self.player.velocity_goal.x = -self.player.MAX_VELOCITY
    elif self.is_move_right and not self.is_move_left:
        self.player.velocity_goal.x = self.player.MAX_VELOCITY
    elif not self.is_move_left and not self.is_move_right:
        self.player.velocity_goal.x = 0
4

1 回答 1

3

我不确定您的矩形字符对于每种可能的键/按钮按下组合应该有什么反应,因为有些是模棱两可的,例如同时按住左右键时 - 所以以下修改(它们是仅限于EventManagement.Listen()方法)可能不会产生完全受欢迎的行为。

在修订版中,如果您在向右移动时按下左键,则在您释放右键之前,视觉上不会发生任何事情,而在相反的情况下会发生相反的情况。无论哪种方式,速度都会平稳变化。

基本上我所做的是将两个速度键的处理实现为事件驱动的有限状态机,它可以处于四种状态之一,表示这两个键的所有可能组合处于向上或向下位置。除此之外,还有 4 个不同的力度键“事件”对应于这些键被按下或释放。

代码有点长,因为它必须处理每个可能状态下的每个可能事件,但这并不是我所说的复杂。可以通过使其成为table-driven来缩短它,这是实现有限状态自动机的另一种方法。

# added constants
LEFT_KEY = K_a
RIGHT_KEY = K_d
LURU, LDRU, LURD, LDRD = range(4)  # velocity states
LD, RD, LU, RU = range(4)  # velocity key events
VEL_EVENTS = {LD, RD, LU, RU}  # all possible velocity key events
MAX_VELOCITY = 200

class EventManagement(object):
    ''' Handles keyboard events.
        Toggles player variables according to the event.
    '''
    def __init__(self, player):
        self.player = player
        self.state = LURU

    def is_doneloop(self, flag):
        global is_doneloop
        is_doneloop = flag
        return is_doneloop

    def listen(self):
        ''' Toggles player variables according to keyboard/mouse input.
        '''
        for event in pygame.event.get():
            vel_event = None

            if event.type == QUIT:
                self.is_doneloop(True)
                break

            if event.type == KEYDOWN:
                if event.key == LEFT_KEY:
                    vel_event = LD
                elif event.key == RIGHT_KEY:
                    vel_event = RD

            if event.type == KEYUP:
                if event.key == K_ESCAPE:
                    self.is_doneloop(True)
                    break
                if event.key == LEFT_KEY:
                    vel_event = LU
                elif event.key == RIGHT_KEY:
                    vel_event = RU

            if vel_event in VEL_EVENTS:
                if self.state == LURU:
                    if vel_event == LD:
                        self.player.velocity_goal.x = -MAX_VELOCITY
                        self.state = LDRU
                    elif vel_event == RD:
                        self.player.velocity_goal.x = MAX_VELOCITY
                        self.state = LURD
                elif self.state == LDRU:
                    if vel_event == RD:
                        self.state = LDRD
                    elif vel_event == LU:
                        self.state = LURU
                        self.player.velocity_goal.x = 0
                elif self.state == LURD:
                    if vel_event == LD:
                        self.state = LDRD
                    elif vel_event == RU:
                        self.state = LURU
                        self.player.velocity_goal.x = 0
                elif self.state == LDRD:
                    if vel_event == LU:
                        self.state = LURD
                        self.player.velocity_goal.x = MAX_VELOCITY
                    elif vel_event == RU:
                        self.state = LDRU
                        self.player.velocity_goal.x = -MAX_VELOCITY

    #-------------------------------------------------------------------------

更新

为了解决您在评论中提到的另一个问题,我认为您需要做几件事。首先,注释掉的行update()

    # self.position = self.position.add(self.velocity) * dt

不起作用,因为它不是 C++ 版本的正确翻译:

    box.vecPosition = box.vecPosition + box.vecVelocity * dt;

因为它先相加positionvelocity然后将结果乘以dt. 所以要修复它,只需让你的相同:

    self.position.x = self.position.x + (self.velocity.x * dt)

这将允许self.velocity.x * dt首先通过标准运算符优先级计算数量,然后将其添加到self.position.x.

即使进行了这种修改,速度的变化也会很慢。我认为这是由于设置velocity_goal.x的值太小(代码中的 +/-7)造成的。相反,使用更大的东西,比如200. 当你使用它时,用一个新的常量替换它们——就像MAX_VELOCITY = 200你只需要在一个地方改变值。

奖金:

Vector虽然当然不是必需的,但您可以通过以下方式编写代码来稍微简化/缩短和加速您的课程:

class Vector(object):
    ''' Performs vector arithmetic
    '''
    def __init__(self, x, y):
        self.x, self. y = x, y

    def add(self, v):
        return Vector(self.x + v.x, self.y + v.y)

    def mult(self, s):
        return Vector(s * self.x, s * self.y)

您可以更进一步定义Vector.__add__(),Vector.__mul__()等,然后能够更自然地使用它们。

最后的建议是将self.ground = {'shape': self.rect, 'color': self.color}and替换self.player = {'shape': self.rect, 'color': self.color}为 justself.shapeself.color属性 - 因为将它们放在单独的字典中没有什么好处,反而只会减慢访问它们的值并使访问变得复杂。

更新 2:

正如我所提到的,FSM 逻辑可以通过使其由表驱动来消除冗余而变得更加紧凑——尽管这样做也会使其更加抽象并且最初可能更难以理解。这就是我的意思:

# added constants
LEFT_KEY = K_a
RIGHT_KEY = K_d
LURU, LDRU, LURD, LDRD = range(4)  # velocity states
LD, RD, LU, RU = range(4)  # velocity key events
VEL_EVENTS = {LD, RD, LU, RU}  # every velocity key event value
NEW_VELOCITY_GOAL, NEW_STATE = range(2)  # indices of EVENT_DECISION_TABLE entries
MAX_VELOCITY = 200

# non-None entries represent new velocity_goal and state value for each event for each state
EVENT_DECISION_TABLE = [
# event       LD                     RD                    LU                    RU             # cur state
    [[-MAX_VELOCITY, LDRU], [MAX_VELOCITY, LURD], [None,         None], [None,          None]], # LURU
    [[None,          None], [None,         LDRD], [0,            LURU], [None,          None]], # LDRU
    [[None,          LDRD], [None,         None], [None,         None], [0,             LURU]], # LURD
    [[None,          None], [None,         None], [MAX_VELOCITY, LURD], [-MAX_VELOCITY, LDRU]], # LDRD
]

class EventManagement(object):
    ''' Handles keyboard event's.
    Toggles player variables according to the event's.
    '''
    def __init__(self, player):
        self.player = player
        self.state = LURU

    def is_doneloop(self, flag):
        global is_doneloop
        is_doneloop = flag
        return is_doneloop

    def listen(self):
        ''' Toggles player variables according to keyboard/mouse input.
        '''
        for event in pygame.event.get():
            vel_event = None

            if event.type == QUIT:
                self.is_doneloop(True)
                break
            elif event.type == KEYDOWN:
                if event.key == LEFT_KEY:
                    vel_event = LD
                elif event.key == RIGHT_KEY:
                    vel_event = RD
            elif event.type == KEYUP:
                if event.key == K_ESCAPE:
                    self.is_doneloop(True)
                    break
                elif event.key == LEFT_KEY:
                    vel_event = LU
                elif event.key == RIGHT_KEY:
                    vel_event = RU

            if vel_event in VEL_EVENTS:
                entry = EVENT_DECISION_TABLE[self.state][vel_event]
                if entry[NEW_VELOCITY_GOAL] is not None:
                    self.player.velocity_goal.x = entry[NEW_VELOCITY_GOAL]
                if entry[NEW_STATE] is not None:
                    self.state = entry[NEW_STATE]

    #-------------------------------------------------------------------------

更新 3

在观看了一些与该方法相关的游戏开发者数学系列视频之后PlayerData.approach(),我想我现在明白了它的作用(以及为什么它的代码让我感到困惑)。

我感到困惑的主要原因是因为它的dt参数不是时间差值,这就是为什么在PlayerData.update()调用它之前它需要乘以另一个幻数。基本上它是每个增量时间的增量速度(也称为加速度)。它的值与最大速度、每秒帧数 (FPS) 以及您希望玩家从零达到该速度所需的时间(平均加速度)有关。

例如,每秒 40 帧,dt value passed toPlayerData.update()` 将为 0.025 秒,因此如果最大速度为 80 或 1000,将其添加到当前速度将几乎没有影响,即使你这样做每秒 40 次。

要了解它应该是什么,首先需要根据从静止开始达到最大速度需要多长时间来定义对象的平均加速度。这只是它的最大速度/加速时间。如果时间以秒为单位,这是每秒的加速量。要找出每帧应该有多少,只需将其除以每秒帧数。

由于dt对于给定的 FPS,is 应该是一个相当恒定的值,因此可以预先计算每帧加速度并将其存储为另一个命名的常数。

实现这一点需要进行以下更改和添加:

# more constants
MAX_VELOCITY = 200
ACCEL_TIME = 1  # secs to accelerate to max velocity (or slow down from it)
AVG_ACCEL = MAX_VELOCITY / float(ACCEL_TIME)  # per sec
ACCEL_PER_FRAME = AVG_ACCEL / FPS

class PlayerData(object):

    ### showing updated methods only

    def approach(self, vel_goal, vel_curr, accel):
        difference = vel_goal - vel_curr
        if difference > accel:
            return vel_curr + accel
        if difference < -accel:
            return vel_curr - accel
        return vel_goal

    def update(self, dt):
        self.velocity.x = self.approach(self.velocity_goal.x,
                                        self.velocity.x, ACCEL_PER_FRAME)
        self.position.x = self.position.x + (self.velocity.x * dt)

        self.player['shape'].top = self.position.y
        self.player['shape'].left = self.position.x
于 2013-11-07T15:12:32.280 回答