Menu
CoddyTech

跑动与跳跃

本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 15 课,共 28 课。

运行只会改变 velocity.x。重力和跳跃只会改变 velocity.y。所以要把这两部分分开设置:

velocity.x = Input.get_axis("move_left", "move_right") * speed

不要像这样设置整个速度:

velocity = Vector2(Input.get_axis("move_left", "move_right") * speed, 0)

这行代码每一帧都会把 velocity.y 设为 0。它会清除下落速度和跳跃效果,所以英雄会飘起来。

challenge icon

挑战

简单

让英雄在下落和跳跃时也能奔跑。

  1. 在 move_and_slide() 上方,将 velocity.x 设为 Input.get_axis("move_left", "move_right") 乘以 speed。
  2. 让 velocity.y 保持由重力和跳跃控制。

按下“开始”:英雄以每秒 220 像素的速度奔跑,并且可以向上和向右跳跃。然后点击“检查”。

亲手试试

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
	move_and_slide()

输入与移动中的所有课

自己练习: Godot 在线编辑器