0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TPS視点でオブジェクトを射出する

Posted at

目的

以下のようなTPS視点でオブジェクトを射出する動作を作りたい

shoot_2.gif

必要な処理

  1. キャラクターを作る
  2. カメラの設定
  3. オブジェクトを作る
  4. オブジェクトを生成、動かす

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);
    }

}

カメラ⇒マウスカーソルの位置へ射出されるようにしています

まとめ

基本的な処理過ぎて探しても載っていなかったためまとめました。
参考になれば幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?