目的
以下のようなTPS視点でオブジェクトを射出する動作を作りたい
必要な処理
- キャラクターを作る
- カメラの設定
- オブジェクトを作る
- オブジェクトを生成、動かす
1.キャラクターを作る
以下を参照しました
https://xr-hub.com/archives/13135
2.カメラの設定
以下を参照しました
https://qiita.com/K_phantom/items/d5d92955043137a59d8f
3.オブジェクトを作る
なんでもよいので、キューブオブジェクト等を作成します
そしてプレハブ化させておきます
4.オブジェクトを生成、動かす
ボタンを押されたときにオブジェクトが生成されるようにスクリプトを記載します
キャラクター(ユニティちゃん)にアタッチしておきます
UnityChanController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnityChanController : MonoBehaviour
{
//ユニティちゃんを格納する変数
public GameObject player;
//プレハブ名
public GameObject BindCube;
//ポジション
private Vector3 playerpos;
private Vector3 bindcubepos;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.X))
{
playerpos = this.transform.position;
bindcubepos = new Vector3(playerpos.x, playerpos.y + 2, playerpos.z);
bindcubepos += transform.forward * 2;
Instantiate(BindCube, bindcubepos, player.gameObject.transform.rotation);
}
}
}
前に生成されるように
.cs
bindcubepos += transform.forward * 2;
としています
プレハブはインスペクターで設定します
そして、射出したいプレハブ化したオブジェクトに
以下のスクリプトをアタッチします。
BindCubeController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BindCubeController : MonoBehaviour
{
//オブジェクトの速度
public float speed = 0.05f;
//オブジェクトの横移動の最大距離
public float max_alive = 10.0f;
//プレハブ
public GameObject BindCube;
//ユニティちゃんを格納する変数
public GameObject player;
// Start is called before the first frame update
void Start()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 worldDir = ray.direction;
GetComponent<BindCubeController>().Shoot(worldDir * 700);
}
// Update is called once per frame
void Update()
{
//オブジェクトが生き残る時間
if (max_alive < 0)
{
Destroy(this.gameObject);
}
max_alive -= Time.deltaTime;
}
public void Shoot(Vector3 dir)
{
GetComponent<Rigidbody>().AddForce(dir);
}
}
カメラ⇒マウスカーソルの位置へ射出されるようにしています
まとめ
基本的な処理過ぎて探しても載っていなかったためまとめました。
参考になれば幸いです。