Menu
CoddyTech

限制在屏幕范围内

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

向左运行后,英雄会离开屏幕。clamp(value, low, high)会将数字限制在两个端点之间。如果value小于low,它会返回low;如果value大于high,它会返回high;否则返回value。clamp(700, 14, 626)的结果是 626。

移动后限制位置,并保存结果:

move_and_slide()
position.x = clamp(position.x, 14, 626)

position是英雄的中心,英雄宽 28 像素。因此,它的中心会与 640 像素宽屏幕的两侧各保持 14 像素的距离,整个英雄都会留在屏幕内。

challenge icon

挑战

简单

让整个英雄角色都保持在屏幕内。

  1. 在 move_and_slide() 之后,用 clamp() 设置 position.x。
  2. 将它限制在 14 和 626 之间。

按“开始”,然后跑向两侧:英雄角色会在边缘停下,并且完全留在屏幕内。然后按“检查”。

亲手试试

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")
	if direction == 0:
		velocity.x = move_toward(velocity.x, 0, friction * delta)
	else:
		velocity.x = move_toward(velocity.x, direction * speed, acceleration * delta)
	if direction > 0:
		$Look.scale.x = 1
	if direction < 0:
		$Look.scale.x = -1
	move_and_slide()

输入与移动中的所有课

自己练习: Godot 在线编辑器