摩擦力
本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 19 课,共 28 课。
大多数游戏角色减速比加速快。松开所有按键时的减速称为摩擦力。
要使用不同的数值来控制停止,代码需要两条路径。else 为 if 提供第二条路径,而且两条路径中恰好有一条会运行:
if direction == 0:
velocity.x = move_toward(velocity.x, 0, friction * delta)
else:
velocity.x = move_toward(velocity.x, direction * speed, acceleration * delta)== 用于检查两个值是否相等。一个 = 用于设置变量。没有按下任何按键时,direction == 0 的结果为 true。
较小的 friction(例如 300)会让角色像在冰面上一样滑行。较大的数值(例如 2400)则会让角色在几帧内停下来。
挑战
中等松开按键时,让英雄快速停下来。
- 把
move_toward这一行放到else:下面。 - 在它上面,在
if direction == 0:下方,用move_toward按friction * delta的幅度将velocity.x减速到0。
按下“开始”,让英雄移动后松开按键:英雄会滑行一小段,然后停下来。然后点击“检查”。
亲手试试
extends CharacterBody2D
var speed = 220
var acceleration = 900
var friction = 2400
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
var direction = Input.get_axis("move_left", "move_right")
velocity.x = move_toward(velocity.x, direction * speed, acceleration * delta)
move_and_slide()
输入与移动中的所有课
自己练习: Godot 在线编辑器