lerp运动和键盘运动按钮 - 快速按下会导致角色卡在原位

时间:2013-11-06 09:25:29

标签: python pygame

所以我决定在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

1 个答案:

答案 0 :(得分:2)

我不确定你的矩形字符对按键/按键按下的每种可能组合应该有什么反应,因为有些是不明确的,例如当同时按下左键和右键时 - 所以进行以下修改(仅适用于EventManagement.Listen()方法)可能无法完全产生所追求的行为。

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

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

代码有点长,因为它必须处理每个可能状态中的每个可能事件,但这不是我称之为复杂的事情。可以通过设置table-driven来缩短它,这是实现finite-state-automata的另一种方式。

# 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 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

            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;

因为它首先将position添加到velocity,然后将结果乘以dt。所以要修复它,只需使它们相同:

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

允许首先通过标准operator precedence计算数量self.velocity.x * dt,然后将其添加到self.position.x

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

加成:

虽然肯定不是必需条件,但您可以通过以这种方式编写代码来略微/缩短和加速Vector课程:

class Vector(object):
    ''' Performs vector aritmetic
    '''
    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}self.player = {'shape': self.rect, 'color': self.color}替换为self.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()方法相关的几个Math for Game Developers系列视频后,我想我现在明白它的作用(以及为什么它的代码让我感到困惑)。

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

例如,每秒40帧,传递给dt的{​​{1}}值将为0.025秒,因此如果最大速度为0,那么将其添加到当前速度几乎没有影响80或1000,即使你每秒40次。

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

由于PlayerData.update()对于给定的FPS应该是相当恒定的,因此可以提前计算每帧加速度并将其存储为另一个命名常量。

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

dt