向上跳跃
本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 13 课,共 28 课。
要跳跃,请在玩家按下 jump 的那一帧,将 velocity.y 设为一个较大的向上速度。向上对应较小的 y 值,所以这个数字是负数:
var jump_velocity = -500
func _physics_process(delta):
velocity.y += gravity * delta
if Input.is_action_just_pressed("jump"):
velocity.y = jump_velocity
move_and_slide()你不需要编写向下的过程。重力会不断加到 velocity.y 上,因此英雄上升时会减速,在顶点停下,然后落回来。
使用 is_action_just_pressed,而不是 is_action_pressed。如果一直按住按键,每一帧都会把速度设为 -500,英雄就会飞出屏幕。
挑战
简单让英雄跳起来。
- 在重力那一行和
move_and_slide()之间,为Input.is_action_just_pressed("jump")添加一个if条件。 - 在其中,将
velocity.y设为jump_velocity。
按“开始”,再按空格键:英雄会跳起来,然后落回地面。按住空格键不会让它一直飞。然后点击“检查”。
亲手试试
extends CharacterBody2D
var gravity = 1000
var jump_velocity = -500
func _physics_process(delta):
velocity.y += gravity * delta
move_and_slide()
输入与移动中的所有课
自己练习: Godot 在线编辑器