Menu
CoddyTech

英雄:平稳奔跑

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

英雄会在一个画面内启动并停下。用 acceleration 让它加速,用 friction 让它停下:

var direction = Input.get_axis("move_left", "move_right")
if direction == 0:
	velocity.x = move_toward(velocity.x, 0, friction * delta)
else:
	velocity.x = move_toward(velocity.x, direction * speed, acceleration * delta)

将 acceleration 设为 1200,将 friction 设为 2400。英雄大约在五分之一秒内达到全速,这样跑到坑边时还有加速空间。

challenge icon

挑战

中等

让英雄平稳加速和停止。

  1. 添加 var acceleration = 1200 和 var friction = 2400。
  2. 将轴向存入 var direction。没有按键按下时,通过 friction * delta 将 velocity.x 平滑移向 0,使用 move_toward。
  3. 按下按键时,通过 acceleration * delta 将速度平滑移向 direction * speed,使用 move_toward。

按“开始”:英雄会逐渐加速,停止时会稍微滑行,并越过坑洞。然后点击“检查”。

亲手试试

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 在线编辑器