マグネット
Coddyの「Unityゲーム:スカイレーン」コースのレッスン 14/20。
パワーアップがあると、走るたびに前回とは違った感覚になります。最初のパワーアップは磁石です。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にpublic float magnetTime = 8f;とpublic float magnet;を追加します。0より大きい間、毎フレーム値をカウントダウンします。- OnTriggerEnter で、
Magnetタグが付いている場合はmagnet = magnetTimeを設定し、取得アイテムを破棄します。 CoinにpullRange = 7fとpullSpeed = 30fを追加し、Start で Runner を取得して、上記のように引き寄せます。RoadにmagnetPrefabを追加します。Fill の最後でfloat roll = Random.value;を設定し、roll < 0.06fの場合は、ランダムなレーンの y 1、z -6 に磁石を配置します。
自分で試してみよう
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プレイグラウンド