甘酒のアプリ開発

一人でも多くの人を幸せにするアプリを作っていけたらなぁと思います。

【Unity】1分でできる。オブジェクトを移動させる方法

今回は、オブジェクトを移動させる方法 について紹介していきます。

 

簡単に実装することができるので、もしよかったら試してみてください。

 

f:id:RenRoku6:20210827174605p:plain

 

 

 

オブジェクトを右移動させるスクリプト

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エディターで確認

f:id:RenRoku6:20210828000824p:plain

先ほど作ったMIGIidou.csを移動させたいオブジェクトにアタッチします。

 

 

ゲームスタートボタンを押して問題なく動作するかをチェックします。

f:id:RenRoku6:20210828001124p:plain

f:id:RenRoku6:20210828000945p:plain

f:id:RenRoku6:20210828000959p:plain





前後、左右、上下に移動させたい場合のスクリプト

前後左右上下に移動させるスクリプトも公開しておきます。

 

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軸を-方向に移動)

 

 

 

終わり。