Caia e reapareça
Parte da seção Criando Jogos de Verdade do Journey de Unity da Coddy. Lição 52 de 60.
Desafio
MédioUma queda deve fazer o jogador voltar.
- Em
Player, adicione[SerializeField] private float fallY = -5f;e um ponto de reaparecimento, definido como a posição inicial emStart(). - Adicione
public void SetCheckpoint(Vector3 point), que define o ponto de reaparecimento. - Quando estiver abaixo de
fallY: definacontroller.enabled = false, mova o jogador para o ponto de reaparecimento, habilite-o novamente e limpevelocity.
Pressione “Jogar” e pule para fora: você estará de volta à plataforma. Depois, pressione “Verificar”.
Experimente você mesmo
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;
}
}
}
Todas as lições de Criando Jogos de Verdade
1Texto na tela
Canvas e textoExiba a pontuaçãoFormate númerosUm cronômetro regressivoRevisão: velocímetro4Cenas e Fases
Carregar uma CenaReiniciar a FasePróxima FaseManter entre CenasRevisão: Seleção de Fases10Projeto: Plataforma 3D
O percursoPlataformas móveis2Botões e telas
Botões e onClickLambdasConectando no InspectorPainéis ligados e desligadosBarras de vidaRevisão: Loja de melhorias5Salvando com PlayerPrefs
Salvar um númeroCarregar com um valor padrãoRecordeSalvar configuraçõesRevisão: Moedas no bancoPratique por conta própria: Playground de Unity