移动道路
Coddy Unity 游戏:天空赛道 课程的第 6 课,共 21 课。
在跑酷游戏中,玩家待在原地,世界向玩家迎面而来。让摄像机和玩家一直向前移动也行,但数值会不断增大;移动道路可以让所有数值都保持在接近零的范围内。
速度属于整个游戏,所以它保存在 GameManager 中。Road 会在 Start 中获取一次速度,并在每帧读取:
float step = game.speed * Time.deltaTime;
foreach (Transform chunk in chunks)
{
chunk.position += Vector3.back * step;
}Vector3.back 表示 (0, 0, -1),也就是朝向摄像机。为了稍后移动这些部分,Road 必须记住它们,并将它们存储在 List<Transform> 中。
挑战
简单让道路朝跑步者移动。
- 在
GameManager中添加public float startSpeed = 10f;和public float speed;,并在 Start 中设置speed = startSpeed。 - 在
Road中添加private List<Transform> chunks = new List<Transform>();(并添加using System.Collections.Generic;)以及private GameManager game;。 - 在 Start 中设置
game = FindFirstObjectByType<GameManager>();,并将每个新路段添加到chunks中。 - 按上面的方式编写
Update。
按下“开始”:道路会朝跑步者快速移动。然后按“检查”。
亲手试试
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 float fallSpeed;
private float slide;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
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;
}
}
Unity 游戏:天空赛道中的所有课
自己练习: Unity 在线编辑器