Godot GDScript代码跳转不工作



我正在制作一款2d从左到右风格的游戏(与《空心之夜》等游戏相同,所以你可以获得控制要点),我在主要玩家的运动体中包含以下代码。这段代码的跳转("up")部分不起作用。向上按似乎没有任何作用,尽管"有效"。是印刷的。重力部分(velocity.y += 1000)可以。我试过把它放入while循环中,然而,甚至连打印都不起作用。

extends KinematicBody2D
export (int) var speed = 200
var velocity = Vector2()
func get_input():
velocity = Vector2()
if Input.is_action_pressed("right"):
velocity.x += 1
if Input.is_action_pressed("left"):
velocity.x -= 1
if Input.is_action_just_pressed("up"):
#this bit doesnt work.
velocity.y -= 1000
#this is printed though
print("Worked")
velocity = velocity.normalized() * speed
func _physics_process(delta):
get_input()
velocity.y += 1000
velocity = move_and_slide(velocity)

让我们来解释一下:velocity.y += 1000依赖于帧速率。实际上,它是每帧每秒1000像素的加速度。你可能想这样做:velocity.y += gravity * delta。式中gravity为加速度,单位为像素/秒的平方。

同样,这些是加速度:velocity.x += 1,velocity.x -= 1。它们以每帧每秒一个像素的速度增加和减少水平速度。但是,您正在通过speed规范化速度和缩放。你能减速和改变方向吗?


关于这个问题,我看到的是:

首先,你擦除速度(这也意味着任何向下的加速度都消失了):

velocity = Vector2()

然后,如果玩家刚刚按下"up",这一行运行:

velocity.y -= 1000

这将导致velocity.y的值为-1000(因为它在之前被擦除为零)。

然后归一化:

velocity = velocity.normalized() * speed

如果我们假设没有水平速度,现在velocity.y-speed(默认)。

之后在同一帧中出现这行:

velocity.y += 1000

这将导致velocity.y的值为1000 - speed。该符号取决于speed是否大于1000

假设它不是(因为它不是默认的),你只是在重力方向上得到一个速度,而不管玩家按下"up"


要解决这个问题,我们需要:

  • 不跳跃时施加重力
  • 只在跳跃时覆盖垂直速度。

实际上,对于水平运动,我也会做类似的事情。

export var speed := 200.0
export var jump_speed := -1000.0
export var gravity := 1000.0

var velocity := Vector2.ZERO

func _physics_process(delta) -> void:
velocity.x = Input.get_axis("left", "right") * speed
if Input.is_action_just_pressed("up"):
velocity.y = jump_speed
else:
velocity.y += gravity * delta
velocity = move_and_slide(velocity)

我已经去掉了get_input,因为它更像compute_velocity,但我们在_physics_process中扰乱了重力的速度。事实上,我们需要delta来正确地做到这一点。

当然这不是水平加速度。你想要水平加速度吗?这将使speed变成最大的speed,对吧?好:

export var speed := 200.0
export var jump_speed := -1000.0
export var acceleration := 100.0
export var gravity := 1000.0

var velocity := Vector2.ZERO

func _physics_process(delta) -> void:
var inpux_x := Input.get_axis("left", "right")
velocity.x = clamp(
velocity.x + input_x * acceleration * delta,
-speed,
speed
)
if Input.is_action_just_pressed("up"):
velocity.y = jump_speed
else:
velocity.y += gravity * delta
velocity = move_and_slide(velocity)

顺便说一下,不,在_physics_process中输入没有错。事实上,这是有意的。


我还注意到你的代码没有基础检查。我就不详述了,因为那不是问题。

最新更新