磁铁
Coddy Unity 游戏:天空赛道 课程的第 14 课,共 21 课。
强化道具会让每次奔跑都与上次有所不同。第一个是磁铁:持续 8 秒,跑者附近的每枚金币都会飞向它。
Runner 会在 magnet 中记录剩余时间,并进行倒计时。每枚金币都会查看跑者的位置;只要磁铁处于启用状态,且跑者在附近,金币就会向跑者移动:
if (runner.magnet > 0f && Vector3.Distance(transform.position, runner.transform.position) < pullRange)
{
transform.position = Vector3.MoveTowards(transform.position, runner.transform.position, pullSpeed * Time.deltaTime);
}金币会飞到跑者身上,触发器会完成剩下的工作。偶尔,一段道路上会出现一个粉色磁铁道具,位于障碍物前方 6 个单位处。
挑战
简单磁铁会把附近的硬币吸向跑步者。
Runner:添加magnetTime = 8f和magnet;当数值大于 0 时,让磁力倒计时。Magnet标签会设置magnet = magnetTime,并销毁拾取物。Coin:添加pullRange = 7f和pullSpeed = 30f,并按上述方式吸引硬币。Road.Fill:使用float roll = Random.value;,当roll < 0.06f时,在随机车道的 y 坐标 1、z 坐标 -6 处放置magnetPrefab。
按“开始”,拿到粉色磁铁:硬币就会飞向你。然后点击“检查”。
亲手试试
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();
}
else if (other.CompareTag("Coin"))
{
game.AddCoin();
Destroy(other.gameObject);
}
}
}
Unity 游戏:天空赛道中的所有课
自己练习: Unity 在线编辑器