gpt4 book ai didi

python - lerp 移动和键盘移动按钮 - 快速按下会导致角色卡在原地

转载 作者:太空宇宙 更新时间:2023-11-04 03:53:51 26 4
gpt4 key购买 nike

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

最佳答案

我不确定您的矩形字符对于每种可能的按键/按钮组合应该有什么 react ,因为有些是模棱两可的,例如同时按住左键和右键时 - 所以以下修改(仅适用于 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 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首先通过标准计算 operator precedence ,然后将其添加到 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}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
看了几期后 Math for Game DevelopersPlayerData.approach() 相关的系列视频方法,我想我现在明白它的作用(以及为什么它的代码让我感到困惑)。
我困惑的主要原因是因为它的 dt参数不是时间差值,这就是为什么它需要在 PlayerData.update() 之前乘以另一个魔数(Magic Number)称它。基本上它是每个增量时间的增量速度(也称为加速度)。它的值与最大速度、每秒帧数 (FPS) 以及您希望玩家从零(平均加速度)达到该速度所需的时间有关。
例如,每秒 40 帧,dt value passed to PlayerData.update()` 将是 0.025 秒,因此如果最大速度为 80 或 1000,即使您每秒执行 40 次,将其添加到当前速度也几乎没有影响。
要了解它应该是什么,首先需要根据从站立开始达到最大速度需要多长时间来定义对象的平均加速度。这只是它的最大速度/加速时间。如果时间以秒为单位,则这是每秒的加速量。要找出每帧应该有多少,只需将其除以每秒帧数。
dt对于给定的 FPS,它应该是一个相当常数,每帧加速度可以提前计算并存储为另一个命名常数。
实现这将需要以下更改和添加:
# 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

关于python - lerp 移动和键盘移动按钮 - 快速按下会导致角色卡在原地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19808183/

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