(Unity)オブジェクトを往復運動させる方法(3つのパターン)

(1)下準備

  • オブジェクトを1つ作成

(2)スクリプトの作成

①PingPongを使用する方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Move_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);
    }
}

 

②Sinを使用する方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Move_Sin : MonoBehaviour
{
    private Vector3 pos;
 
    void Start()
    {
        pos = transform.position;
    }
 
    void Update()
    {
        transform.position = new Vector3(pos.x + Mathf.Sin(Time.time) * 5, pos.y, pos.z);
    }
}

 

③Positionを変化させる方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Move_Position : MonoBehaviour
{
    public float speed;
    private Vector3 pos;
    private bool isStop = false;
 
    void Start()
    {
        pos = transform.position;
    }
 
    void Update()
    {
        if (!isStop)
        {
            pos.x += Time.deltaTime * speed; // speedは移動速度
            transform.position = pos;
 
            if (pos.x > 15) // 終点(自由に変更可能)
            {
                isStop = true;
            }
        }
        else
        {
            pos.x -= Time.deltaTime * speed;
            transform.position = pos;
 
            if (pos.x < 0) // 始点(自由に変更可能)
            {
                isStop = false;
            }
        }
    }
}