Rơi xuống và xuất hiện lại
Thuộc phần Xây dựng trò chơi thực tế trong hành trình Unity của Coddy. Bài học 52 trên 60.
Thử thách
Trung bìnhKhi rơi, người chơi cần quay lại vị trí ban đầu.
- Trong
Player, thêm[SerializeField] private float fallY = -5f;và một điểm hồi sinh, đặt điểm này ở vị trí bắt đầu trongStart(). - Thêm
public void SetCheckpoint(Vector3 point)để đặt điểm hồi sinh. - Khi vị trí thấp hơn
fallY: đặtcontroller.enabled = false, di chuyển đến điểm hồi sinh, bật lại rồi xóavelocity.
Nhấn Chơi rồi nhảy xuống: bạn sẽ quay lại bệ. Sau đó nhấn Kiểm tra.
Tự làm thử
using UnityEngine;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour
{
[SerializeField] private float speed = 5f;
[SerializeField] private float jumpHeight = 1.5f;
[SerializeField] private float gravity = -9.81f;
private CharacterController controller;
private InputAction moveAction;
private InputAction jumpAction;
private Vector3 velocity;
private MovingPlatform platform;
void Start()
{
controller = GetComponent<CharacterController>();
moveAction = InputSystem.actions.FindAction("Move");
jumpAction = InputSystem.actions.FindAction("Jump");
}
void Update()
{
if (controller.isGrounded && velocity.y < 0f)
{
velocity.y = -2f;
}
Vector2 input = moveAction.ReadValue<Vector2>();
Vector3 move = new Vector3(input.x, 0f, input.y) * speed;
if (jumpAction.WasPressedThisFrame() && controller.isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
Vector3 motion = (move + velocity) * Time.deltaTime;
if (platform != null)
{
motion += platform.delta;
platform = null;
}
controller.Move(motion);
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
if (hit.normal.y > 0.5f && hit.gameObject.TryGetComponent(out MovingPlatform moving))
{
platform = moving;
}
}
}
Tất cả bài học trong Xây dựng trò chơi thực tế
1Văn bản trên màn hình
Canvas và văn bảnHiển thị điểm sốĐịnh dạng sốĐồng hồ đếm ngượcÔn tập: Đồng hồ tốc độ7Điều khiển thời gian
Tạm dừng bằng timeScaleChuyển động chậmThời gian không bị co giãnÔn tập: Bullet Time10Dự án: trò chơi đi cảnh 3D
Đường đuaBệ di chuyển2Nút bấm và màn hình
Nút bấm và onClickLambdaKết nối trong InspectorBật và tắt bảngThanh máuÔn tập: Cửa hàng nâng cấp5Lưu dữ liệu với PlayerPrefs
Lưu một sốTải với giá trị mặc địnhĐiểm cao nhấtLưu cài đặtÔn tập: Tiền xu trong ngân hàngTự luyện tập: Playground Unity