Menu
CoddyTech

Anh hùng: quay lại điểm xuất phát

Thuộc phần Đầu vào và di chuyển trong hành trình Godot của Coddy. Bài học 27 trên 28.

Nếu nhân vật chính rơi xuống hố, nhân vật nên quay lại điểm bắt đầu.

Lưu điểm bắt đầu vào một biến trong _ready(), hàm này chạy trước khi nhân vật di chuyển:

var start_position = Vector2()

func _ready():
	start_position = position

Sau move_and_slide(), hãy kiểm tra xem nhân vật có rơi xuống dưới màn hình cao 360 pixel hay không. Đưa nhân vật trở lại điểm bắt đầu và đặt lại vận tốc để nhân vật không đến nơi trong trạng thái vẫn đang rơi:

if position.y > 400:
	position = start_position
	velocity = Vector2(0, 0)
challenge icon

Thử thách

Trung bình

Đưa nhân vật về vị trí bắt đầu khi rơi xuống hố.

  1. Thêm var start_position = Vector2(), rồi trong một hàm _ready() mới, gán giá trị position cho biến này.
  2. Sau move_and_slide(), khi position.y > 400, đặt position thành start_position và velocity thành Vector2(0, 0).

Nhấn Chơi rồi rơi xuống hố: nhân vật sẽ trở về vị trí bắt đầu. Sau đó nhấn Kiểm tra.

Tự làm thử

extends CharacterBody2D

var speed = 220
var acceleration = 1200
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()

Tất cả bài học trong Đầu vào và di chuyển

Tự luyện tập: Playground Godot