今回は、オブジェクトを移動させる方法 について紹介していきます。
簡単に実装することができるので、もしよかったら試してみてください。
オブジェクトを右移動させるスクリプト
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MIGIidou : MonoBehaviour
{
void Update()
{
Vector3 pos = this.gameObject.transform.position;
this.gameObject.transform.position = new Vector3(pos.x + 0.05f, pos.y, pos.z);
}
}
上記のような スクリプトを作ります。
そのままコピペしてもらえればOKです。
今回は右に移動させます
実際にUnityエディターで確認
先ほど作ったMIGIidou.csを移動させたいオブジェクトにアタッチします。
ゲームスタートボタンを押して問題なく動作するかをチェックします。
前後、左右、上下に移動させたい場合のスクリプト
前後、左右、上下、に移動させるスクリプトも公開しておきます。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MAEidou : MonoBehaviour
{
void Update()
{
Vector3 pos = this.gameObject.transform.position;
this.gameObject.transform.position = new Vector3(pos.x, pos.y, pos.z + 0.05f);
}
}
前に移動する場合のスクリプト。(Z軸を+方向に移動)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class USHIROidou : MonoBehaviour
{
void Update()
{
Vector3 pos = this.gameObject.transform.position;
this.gameObject.transform.position = new Vector3(pos.x, pos.y, pos.z - 0.05f);
}
}
後ろに移動する場合のスクリプト。(Z軸を-方向に移動)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MIGIidou : MonoBehaviour
{
void Update()
{
Vector3 pos = this.gameObject.transform.position;
this.gameObject.transform.position = new Vector3(pos.x + 0.05f, pos.y, pos.z);
}
}
右に移動する場合のスクリプト。(X軸を+方向に移動)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HIDARIidou : MonoBehaviour
{
void Update()
{
Vector3 pos = this.gameObject.transform.position;
this.gameObject.transform.position = new Vector3(pos.x - 0.05f, pos.y, pos.z);
}
}
左に移動する場合のスクリプト。(X軸を-方向に移動)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UEidou : MonoBehaviour
{
void Update()
{
Vector3 pos = this.gameObject.transform.position;
this.gameObject.transform.position = new Vector3(pos.x, pos.y + 0.05f, pos.z);
}
}
上に移動する場合のスクリプト。(Y軸を+方向に移動)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SHITAidou : MonoBehaviour
{
void Update()
{
Vector3 pos = this.gameObject.transform.position;
this.gameObject.transform.position = new Vector3(pos.x, pos.y - 0.05f, pos.z);
}
}
下に移動する場合のスクリプト。(Y軸を-方向に移動)
終わり。