可变高度跳跃
本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 16 课,共 28 课。
在大多数平台游戏中,轻按按钮会让角色小跳一下,按住按钮则会完成一次完整跳跃。
要做到这一点,在松开按钮时缩短跳跃。按键松开的那一帧,Input.is_action_just_released("jump") 的值为 true。如果此时英雄仍在上升,就把它向上的速度减半:
if Input.is_action_just_released("jump") and velocity.y < 0:
velocity.y = velocity.y / 2velocity.y < 0 表示英雄仍在上升。如果没有这个条件,在下落途中松开按键也会减慢下落速度。
如果一直按住按键,直到跳跃到达最高点,就不会缩短跳跃。
挑战
中等轻点跳跃键,让角色小跳一下。
- 在跳跃的
if后面,添加一个if,检查Input.is_action_just_released("jump")和velocity.y < 0。 - 在其中,将
velocity.y减半。
按“开始”:快速轻点空格键会让角色小跳,按住空格键则会完成完整跳跃。然后点击“检查”。
亲手试试
extends CharacterBody2D
var speed = 220
var gravity = 1000
var jump_velocity = -500
func _physics_process(delta):
velocity.y += gravity * delta
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = jump_velocity
velocity.x = Input.get_axis("move_left", "move_right") * speed
move_and_slide()
输入与移动中的所有课
自己练习: Godot 在线编辑器