LoginSignup
0
1

More than 3 years have passed since last update.

ゲームでよくあるアイテムが手前に来るやつ

Posted at

ゲームでよくあるやつ

先日、推しが配信で「フードデリバリーサービス」というゲームをプレイしていた。
そのゲームの以下のような描写を見て「作れそう」と思ったので作りました。
コンポ 2.gif

ソースコード

LookingItemBehaviour.cs
using UnityEngine;

public class LookingItemBehaviour : MonoBehaviour
{
    [SerializeField]
    private Transform target;

    [SerializeField] 
    private float moveDuration = 2f;

    private float moveProgress = 0f;

    private bool isNeedMove = false;

    private bool isNeedReturn = false;

    private Vector3 startPosition;

    private Quaternion startRotation;

    void Start()
    {
        startPosition = transform.position;
        startRotation = transform.rotation;
    }

    void Update()
    {
        // Test
        if (Input.GetKeyDown(KeyCode.Return)) StartMove();
        if (Input.GetKeyDown(KeyCode.Space)) StartReturn();

        if (isNeedMove)
        {
            moveProgress += Time.deltaTime / moveDuration;
            if (moveProgress >= 1f) moveProgress = 1f;
            transform.position = Vector3.Lerp(startPosition, target.position, moveProgress);
            transform.rotation = Quaternion.Lerp(startRotation, target.rotation, moveProgress);
        }
        else if(isNeedReturn)
        {
            moveProgress -= Time.deltaTime / moveDuration;
            if (moveProgress <= 0f) moveProgress = 0f;
            transform.position = Vector3.Lerp(startPosition, target.position, moveProgress);
            transform.rotation = Quaternion.Lerp(startRotation, target.rotation, moveProgress);
        }
    }

    public void StartMove()
    {
        isNeedMove = true;
        isNeedReturn = false;
    }

    public void StartReturn()
    {
        isNeedReturn = true;
        isNeedMove = false;
    }

}

仕組みはいたって単純
ターゲットを指定してそのターゲットと同じpositionとrotationに指定時間で変化するというもの。

動作テスト

SmartPhoneというオブジェクトにLookingItemBehaviourをアタッチしています。
シーンビューの赤い球がtargetに指定してあるItemPositionの位置です。
image.png
テスト用にEnterキーで手前に、Spaceキーで元の場所に戻るようコード内に記述をしています。
以下、動作している様子
コンポ 3.gif
うごいたー

今後の改良

このままではゲームに組み込みづらいので移動終了時のイベントなどを追加してもっと汎用的に使えるよう改良しようと思います。いつか

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1