LoginSignup
27
23

More than 5 years have passed since last update.

[Unity] 当たり判定のある線を引く 〜超簡易版〜

Posted at

Game画面をなぞると線が引けて、かつそれに当たり判定を付けたい場合、簡易的なものをサラッと実装できる方法をまとめておきます。

色々と粗が目立ちますが大目にみてください。。
超簡易版なので。。

事前準備

  1. 空のオブジェクトを作っておきます。これに後述のスクリプトを追加します。
  2. Cubeを作り、Prefab化しておきます。パラメータなどは何も変えなくていいです。

スクリプト

drawPhysicsLine
using UnityEngine;
using System.Collections;

public class drawPhysicsLine : MonoBehaviour
{

    public GameObject linePrefab;
    public float lineLength = 0.2f;
    public float lineWidth = 0.1f;

    private Vector3 touchPos;

    void Start(){

    }

    void Update (){
        drawLine ();
    }

    void drawLine(){

        if(Input.GetMouseButtonDown(0))
        {
            touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            touchPos.z=0;
        }

        if(Input.GetMouseButton(0))
        {

            Vector3 startPos = touchPos;
            Vector3 endPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            endPos.z=0;

            if((endPos-startPos).magnitude > lineLength){
                GameObject obj = Instantiate(linePrefab, transform.position, transform.rotation) as GameObject;
                obj.transform.position = (startPos+endPos)/2;
                obj.transform.right = (endPos-startPos).normalized;

                obj.transform.localScale = new Vector3( (endPos-startPos).magnitude, lineWidth , lineWidth );

                obj.transform.parent = this.transform;

                touchPos = endPos;
            }
        }
    }
}

使い方

事前準備で作成した空のオブジェクトに上記のスクリプトを追加します。
追加するとこのような↓状態になりますので、
drawPhysicsLine.png
Line Prefabのところに事前準備で作成したCubeのPrefabをDrag&Dropで設定します。
あとは実行してGame画面上でマウスを左クリックすれば線が引けます。

Cubeの色を変えれば線の色を変えられます。
Line Lengthは線の最小の長さです。このパラメータ以上の距離をドラッグしないと線が描画されません。数値を1.0とかにすればわかりやすいです。
Line Widthは線の幅です。

27
23
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
27
23