硬币
Coddy Unity 游戏:天空赛道 课程的第 13 课,共 21 课。
金币能让玩家在没有障碍物阻挡时也有理由变换跑道。每个路段都会在障碍物之后、路段上的 4、7、10 和 13 处,以及 y 为 1 的位置,在同一条跑道上排成一列放置 4 枚金币。
金币会自行旋转,使用自己的脚本:
void Update()
{
transform.Rotate(0f, 0f, spinSpeed * Time.deltaTime);
}金币预制体是侧放的,所以它自己的 z 轴朝上:绕 z 轴旋转时,它会像桌上的硬币一样转动。
收集金币是 Runner 的工作,在同一个 OnTriggerEnter 中完成:金币会通过 game.AddCoin() 增加一枚金币,然后被销毁。
挑战
简单在道路上排列硬币,供你收集。
Coin:添加public float spinSpeed = 180f;和上面的 Update。Road.Fill:在末尾,将 4 个coinPrefab放在随机的一条车道上,y 为 1,z 为4f + i * 3f。GameManager:添加coinText、coins和AddCoin();ShowScore 也会设置coinText.text = "Coins: " + coins;。Runner.OnTriggerEnter:Coin标签会调用game.AddCoin()并销毁硬币。
按下“开始”:你收集硬币时,硬币数量会增加。然后点击“检查”。
亲手试试
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 在线编辑器