今回はRigidbodyを付与せず、TranslateやRotateで物体を移動させてみよう。
1.3Dでプロジェクトを作成したら3dギズモを以下のように調整する
![](https://joytas.net/wp-content/uploads/2020/06/img1.png)
2.弾丸の作成
弾丸を作成する。create->3d->Cylinderを原点に作成する
![](https://joytas.net/wp-content/uploads/2020/06/img2.png)
ただこれだと物体の前方を表すz軸が奥を向いてしまっている。(画面の奥を指している)
![](https://joytas.net/wp-content/uploads/2020/06/img3.png)
3.z軸の変更。こういった場合はオブジェクトに親を設定をする。まずは原点にCreateEmptyする。
![](https://joytas.net/wp-content/uploads/2020/06/img4.png)
CreateEmptyした際には必ずtransformをresetする習慣をつけるとよい
![](https://joytas.net/wp-content/uploads/2020/06/img5.png)
4.以下のようにcreateEmptyしたgameobjectの子要素にcylinderを設定し、rotationのxを90度に設定する。
![](https://joytas.net/wp-content/uploads/2020/06/img6-1024x439.png)
5.親子構造にして子要素を90度回すことによってz軸の向きを変えることができた。bulletと名前を変更しておこう。(下の図は見る角度を変えている)
![](https://joytas.net/wp-content/uploads/2020/06/img7-1024x603.png)
6.BulletScriptの作成。ProjectビューのCreate->C#スクリプトからBulletScriptを作成する。
![](https://joytas.net/wp-content/uploads/2020/06/img9.png)
7.BulletScriptを以下のように記述する。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScript : MonoBehaviour
{
void Update()
{
transform.Translate(Vector3.forward);
}
}
8.作成したBulletScriptをドラッグ&ドロップでbulletにアタッチする。
![](https://joytas.net/wp-content/uploads/2020/06/img10-408x1024.png)
9.実行してみよう。画面奥に進んでいくはずだ。ためしにbulletの角度xを-30度にしてもう一度実行してみよう。
![](https://joytas.net/wp-content/uploads/2020/06/img11-1024x349.png)
-30度の方向に飛んでいった。これで弾丸はOKなのでプロジェクトにドラッグ&ドラッグしてプレファブ化しておこう。bulletはヒエラルキーにはもう不要なので削除しておく
![](https://joytas.net/wp-content/uploads/2020/06/img13.png)
10.スペースシップを作成する。Createから3dobjectでCubeを選択する。
![](https://joytas.net/wp-content/uploads/2020/06/img14-1024x195.png)
11.今作ったCubeを右クリックして新たにCreateからCubeを作成する。こうすることで子要素としてオブジェクトを作成することができる。子要素のインスペクターを以下のように設定する
![](https://joytas.net/wp-content/uploads/2020/06/img15-1024x176.png)
12.Shipとリネームする
![](https://joytas.net/wp-content/uploads/2020/06/img16-1024x927.png)
13.ShipScriptを以下のように作成する。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShipScript : MonoBehaviour
{
public GameObject prefab;
Vector3 vec;
public float speed;
void Update()
{
vec.x = Input.GetAxis("Horizontal");
transform.Rotate(Input.GetAxis("Vertical"), 0, 0);
transform.Translate(vec * speed);
if (Input.GetButtonDown("Jump")) {
GameObject bullet = Instantiate(
prefab,
transform.position,
transform.rotation*Quaternion.Euler(-90f,0,0)
//Quaternion.LookRotation(Quaternion.Euler(-90f, 0, 0) * transform.forward)
);
}
}
}
14.ShipにShipScriptをアタッチしたらインスペクターからbulletプレファブを登録する。speedは1とした。
![](https://joytas.net/wp-content/uploads/2020/06/img17-1024x368.png)
コメント