こんにちは!今回は、Unityで2つのオブジェクト間の中間地点を見つけて、別のオブジェクトをその位置に動かす方法を紹介します。この方法を使えば、ゲームオブジェクトの配置がもっと簡単になりますよ。
ステップ1:オブジェクトを用意する
まず、Unityのシーンにオブジェクトを配置します。ここでは、CubeとCylinderとSphereのオブジェクトを使うことにします。
- Hierarchyウィンドウで右クリックし、「3D Object」→「Cube」を選択します。これがプレーヤーオブジェクトになります。
- 同じように、「3D Object」→「Cylinder」を選択します。
- 同じように、「3D Object」→「Sphere」を選択します。CubeとCylinderの中間地点に移動するオブジェクトになります。
![](https://cbagames.jp/wp-content/uploads/2024/02/2024-02-15_214111.png)
ステップ2:Cubeを動かすスクリプト
次に、2つのオブジェクト間の中間地点を計算するスクリプトを作成します。
- Projectウィンドウで右クリックし、「Create」→「C# Script」を選択します。スクリプト名は「PlayerMove」にします。
- スクリプトを開き、以下のコードを入力します。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
void Update()
{
float dx = Input.GetAxis("Horizontal") * Time.deltaTime * 3.0f;
float dz = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;
transform.position = new Vector3
(
transform.position.x + dx, 0.5f, transform.position.z + dz
);
}
}
スクリプトをオブジェクトにアタッチする
Cubeに、スクリプトをアタッチします。
- Cube3を選択し、Inspectorウィンドウに移動します。
- Projectウィンドウで先ほど作成したPlayerMoveスクリプトを見つけ、Cubeにドラッグ&ドロップします。
ステップ3:中間地点を計算するスクリプトを作成する
次に、2つのオブジェクト間の中間地点を計算するスクリプトを作成します。
- Projectウィンドウで右クリックし、「Create」→「C# Script」を選択します。スクリプト名は「SpherePos」にします。
- スクリプトを開き、以下のコードを入力します。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpherePos : MonoBehaviour
{
public GameObject cube;
public GameObject cylinder;
void Start()
{
Vector3 Apos = cube.transform.position;
Vector3 Bpos = cylinder.transform.position;
}
void Update(){
this.transform.position = (cube.transform.position + cylinder.transform.position) / 2;
}
}
スクリプトをオブジェクトにアタッチする
Sphireに、スクリプトをアタッチし、適切なオブジェクトを設定します。
- Sphireを選択し、Inspectorウィンドウに移動します。
- Projectウィンドウで先ほど作成したSpherePosスクリプトを見つけ、Sphireにドラッグ&ドロップします。
- SphireのInspectorウィンドウに表示されるSpherePosスクリプトのフィールドに、CubeとCylinderをそれぞれドラッグ&ドロップして設定します。
![](https://cbagames.jp/wp-content/uploads/2024/02/2024-02-15_214826.png)
ステップ4:オブジェクトを動かしてみる
これで、CubeとCylinderの中間地点にSphereが移動するようになります。シーンを再生すると、CubeとCylinderの位置が変わると、それに応じてSphereも動くのが確認できるでしょう。
この方法は、キャラクターやオブジェクトを特定の位置に配置したいときにとても便利です。ぜひ試してみてください!
おすすめのアセット
「Ultimate Asset Bundle – Complete Asset Collection」は、ゲーム開発に必要なさまざまなアセットをひとまとめにしたお得なパックです。このコレクションには、3Dモデル、テクスチャ、サウンドエフェクト、スクリプトなど、多くの素材が含まれており、初心者からプロまで幅広い開発者に役立ちます。