你跑了多远
Coddy Unity 游戏:天空赛道 课程的第 8 课,共 21 课。
跑步角色前进的距离与道路移动的距离相同:每一帧都把速度乘以时间后累加。
void Update()
{
distance += speed * Time.deltaTime;
ShowScore();
}场景左上角有一段文本,名为 ScoreText,它是 TextMeshPro 文本。它的脚本类型是 TMP_Text(使用 using TMPro;),要显示的文字是 scoreText.text。显示整数米数:(int)distance 会舍去小数点后的部分。
挑战
简单统计跑步者跑了多远。
- 在
GameManager中添加using TMPro;、public TMP_Text scoreText;和public float distance;。 - 添加
ShowScore():scoreText.text = ((int)distance).ToString();。 - 按上面的内容编写 Update,并在 Start 的末尾也调用
ShowScore()。
按“开始”:左上角的数字会统计跑过的米数。然后按“检查”。
亲手试试
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 在线编辑器