跳跃、滑行或躲避
Coddy Unity 游戏:天空赛道 课程的第 11 课,共 21 课。
一种障碍只对应一个答案:跳跃。三种障碍需要三种应对方式:
道路上的红色障碍物,高度为 y 0.5:跳过去;悬挂在 y 1.95 处的黄色横杆:从下方滑过;高度为 y 1.5、三单位高的紫色墙:切换车道。
横杆和墙也标记为 Obstacle,因此你之前编写的碰撞逻辑已经会让游戏在撞上它们时结束。下面两个小方法可以将类型编号转换为预制件和高度:
GameObject Obstacle(int kind)
{
if (kind == 0) return barrierPrefab;
if (kind == 1) return barPrefab;
return wallPrefab;
}挑战
简单添加横杆,让角色从下面滑行通过;添加墙壁,让角色躲开。
- 将
barPrefab和wallPrefab添加到Road。 - 按上面的写法编写
Obstacle(kind),并编写Height(kind):kind 为 0 时返回0.5f,kind 为 1 时返回1.95f,墙壁则返回1.5f。 - 在
Fill中,选择int kind = Random.Range(0, 3);,并在Height(kind)指定的高度放置Obstacle(kind)。
按下 Play:障碍栏、横杆和墙壁会沿着道路向你驶来,碰到其中任何一个都会结束本次游戏。然后点击 Check。
亲手试试
using UnityEngine;
public class Runner : MonoBehaviour
{
public float laneWidth = 2.5f;
public float laneSpeed = 16f;
public float jumpHeight = 1.6f;
public float gravity = -40f;
public float slideTime = 0.7f;
public int lane;
private CharacterController controller;
private GameManager game;
private float fallSpeed;
private float slide;
void Start()
{
controller = GetComponent<CharacterController>();
game = FindFirstObjectByType<GameManager>();
}
void Update()
{
if (!game.over)
{
if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) lane = Mathf.Max(-1, lane - 1);
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) lane = Mathf.Min(1, lane + 1);
bool jump = Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space);
if (jump && controller.isGrounded)
{
fallSpeed = Mathf.Sqrt(jumpHeight * -2f * gravity);
StopSlide();
}
if ((Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) && controller.isGrounded)
{
slide = slideTime;
Resize(0.5f);
}
}
if (slide > 0f)
{
slide -= Time.deltaTime;
if (slide <= 0f) StopSlide();
}
if (controller.isGrounded && fallSpeed < 0f) fallSpeed = -2f;
fallSpeed += gravity * Time.deltaTime;
float targetX = lane * laneWidth;
float x = Mathf.MoveTowards(transform.position.x, targetX, laneSpeed * Time.deltaTime);
Vector3 move = new Vector3(x - transform.position.x, fallSpeed * Time.deltaTime, 0f);
controller.Move(move);
}
void StopSlide()
{
if (transform.localScale.y < 1f) Resize(1f);
slide = 0f;
}
void Resize(float height)
{
controller.enabled = false;
transform.position += Vector3.up * (height - transform.localScale.y);
transform.localScale = new Vector3(1f, height, 1f);
controller.enabled = true;
}
void OnTriggerEnter(Collider other)
{
if (game.over) return;
if (other.CompareTag("Obstacle"))
{
game.GameOver();
}
}
}
Unity 游戏:天空赛道中的所有课
自己练习: Unity 在线编辑器