跌落并重生
本课属于 Coddy Unity 学习旅程的“打造真正的游戏”单元。第 52 课,共 60 课。
挑战
中等掉落后,玩家应该回到原处。
- 在
Player中,添加[SerializeField] private float fallY = -5f;和一个重生点,并在Start()中将其设为起始位置。 - 添加
public void SetCheckpoint(Vector3 point),用于设置重生点。 - 当位置低于
fallY时:设置controller.enabled = false,移动到重生点,再次启用控制器并清空velocity。
按下 Play 并跳下去:你会回到垫子上。然后点击“检查”。
亲手试试
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;
}
}
}
打造真正的游戏中的所有课
自己练习: Unity 在线编辑器