将非常基本的引力应用到 pygame
Implementing very basic gravity into pygame
在我的程序中,我使用按键检测来移动播放器。
尽管其他人已经问过如何获得工作引力,但我想找出一个非常具体的事情,我将如何通过伪代码在真实代码中做到这一点。
if keys 1
pos[1] ++
unless you just jumped
基本上允许我从主游戏循环的前几个循环中获取输入。
有几种方法可以做到这一点。
1.) 您可以使用全局状态来跟踪按键布尔值。在跳跃前检查它是"false",在跳跃时将它设置为"true",在着陆时将它设置回"false"。有些游戏允许双跳,因此您可以递增和递减按键计数器。
global has_jumped = False
if keys 1 and has_jumped is False:
pos[1] ++
has_jumped is True
// Apply gravity here.
if pos[1] <= 0: // Presumes ground is at Y = 0
has_jumped is False
2.) 或者,更稳健的方法是计算玩家是否站在地图上,并使用它来决定角色是否可以跳跃。
global player_acceleration_y = -10 // Gravity, in delta pixels per loop
global player_velocity_y = 0 // Velocity in pixels per loop
function loop():
pos[1] += player_velocity_y
player_velocity_y += player_acceleration_y
if pos[1] <= 0: // Just using a ground plane of 0 here. You could use more complex collision logic here.
pos[1] = 0 // Make sure we don't fall through the floor.
player_velocity_y = 0 // Stop falling.
if keys 1: // Jump
if pos[1] <= 0:
player_velocity_y = 30 // Jump up at a rate of 30 pixels per loop, which will be offset by gravity over time.
在我的程序中,我使用按键检测来移动播放器。 尽管其他人已经问过如何获得工作引力,但我想找出一个非常具体的事情,我将如何通过伪代码在真实代码中做到这一点。
if keys 1
pos[1] ++
unless you just jumped
基本上允许我从主游戏循环的前几个循环中获取输入。
有几种方法可以做到这一点。
1.) 您可以使用全局状态来跟踪按键布尔值。在跳跃前检查它是"false",在跳跃时将它设置为"true",在着陆时将它设置回"false"。有些游戏允许双跳,因此您可以递增和递减按键计数器。
global has_jumped = False
if keys 1 and has_jumped is False:
pos[1] ++
has_jumped is True
// Apply gravity here.
if pos[1] <= 0: // Presumes ground is at Y = 0
has_jumped is False
2.) 或者,更稳健的方法是计算玩家是否站在地图上,并使用它来决定角色是否可以跳跃。
global player_acceleration_y = -10 // Gravity, in delta pixels per loop
global player_velocity_y = 0 // Velocity in pixels per loop
function loop():
pos[1] += player_velocity_y
player_velocity_y += player_acceleration_y
if pos[1] <= 0: // Just using a ground plane of 0 here. You could use more complex collision logic here.
pos[1] = 0 // Make sure we don't fall through the floor.
player_velocity_y = 0 // Stop falling.
if keys 1: // Jump
if pos[1] <= 0:
player_velocity_y = 30 // Jump up at a rate of 30 pixels per loop, which will be offset by gravity over time.