逐渐加速
本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 18 课,共 28 课。
英雄会在一帧内达到全速,也会在一帧内停下,感觉很僵硬。
move_toward(from, to, step) 会让数值 from 朝 to 移动,最多移动 step,不会超过目标值。move_toward(0, 220, 15) 的结果是 15。每帧重复调用,结果会依次变成 30、45,直到达到 220。
将它用于 velocity.x,让速度朝按键要求的方向变化:
var direction = Input.get_axis("move_left", "move_right")
velocity.x = move_toward(velocity.x, direction * speed, acceleration * delta)acceleration 表示每秒增加的速度,所以要乘以 delta。设为 900 时,英雄大约用四分之一秒达到 220。没有按住任何按键时,目标值为 0,所以英雄会减速并停下。
挑战
中等让英雄平滑地加速和减速。
- 将
Input.get_axis("move_left", "move_right")存入var direction。 - 使用
move_toward(velocity.x, direction * speed, acceleration * delta)设置velocity.x。
按下“开始”并按住一个方向键:英雄会逐渐加速到 220,松开按键后会减速。然后点击“检查”。
亲手试试
extends CharacterBody2D
var speed = 220
var acceleration = 900
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 在线编辑器