ブログ

オブジェクトの往復運動

1)PingPongバージョン
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Floor_PingPong : MonoBehaviour
{
    private Vector3 pos;
   
    void Start()
    {
        pos = transform.position;
    }

    void Update()
    {
        transform.position = new Vector3(pos.x + Mathf.PingPong(Time.time, 5), pos.y, pos.z);  
    }
}

2)Sinバージョン
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Floor_Sin : MonoBehaviour
{
    private Vector3 pos;
  
    private void Start()
    {
        pos = transform.position;
    }

    private void Update()
    {
        transform.position = new Vector3(pos.x + Mathf.Sin(Time.time) * 3, pos.y, pos.z);
    }
}

3)Translateバージョン
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Floor_Translate : MonoBehaviour
{
    private Vector3 pos;
    private bool isRight = true;

    private void Update()
    {
        pos = transform.position;

        if(pos.x <= 12.5f && isRight) { transform.Translate(Vector3.right * Time.deltaTime); } if (pos.x > 12.5f)
        {
            isRight = false;
        }

        if (pos.x >= 7.5f && !isRight)
        {
            transform.Translate(-Vector3.right * Time.deltaTime);
        }

        if (pos.x < 7.5f)
        {
            isRight = true;
        }
    }
}