6
5

More than 5 years have passed since last update.

2Dゲームでオブジェクトをつかんで、ドラッグで動かして当たり判定を出す方法

Last updated at Posted at 2016-07-07

こんにちは、この記事では2Dゲームで1つのオブジェクトをつかんでドラッグで動かして、もう1つのオブジェクトとの当たり判定を出す方法をまとめます。

手順

1、2D ObjectからSpriteを選択、動かしたい画像を入れる
2、もう1つSpriteを出して、当たり判定を出したい画像を入れる、タグもつける
3、2つのObjectに2DColliderとRigidbody2Dをつける
4、スクリプトを書く
5、動かしたい画像に関連付ける

1、2D ObjectからSpriteを選択、動かしたい画像を入れる

スクリーンショット 2016-07-07 11.33.26.png

スクリーンショット 2016-07-07 11.34.00.png

2、もう1つSpriteを出して、当たり判定を出したい画像を入れる、タグもつける

1と全く同じように画像を表示させます
また、後で当たり判定を出す際にタグをつけなければならないのでここでつけます。

スクリーンショット 2016-07-07 14.55.13.png

スクリーンショット 2016-07-07 14.55.27.png

Tagのところを選択して、自分で作ったタグにします。ここではflowerというタグにします

3、2つのObjectに2DColliderとRigidbody2Dをつける

スクリーンショット 2016-07-07 14.40.03.png

Is Kinematicにチェックをつけないと落ちていってしまうので注意してください。

4、スクリプトを書く

そのObjectに触った時につかんでドラッグして動くようなスクリプトを書きます
ここではスクリプトの名前をmouseとします。

mouse.cs
using UnityEngine;
using System.Collections;

public class mouse : MonoBehaviour {
    private Vector3 screenPoint;
    private Vector3 offset;

    void OnMouseDown() {
        this.screenPoint = Camera.main.WorldToScreenPoint(transform.position);
        this.offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    void OnMouseDrag() {
        Vector3 currentScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenPoint) + this.offset;
        transform.position = currentPosition;
    }
}

そして、flowerというタグが付いているObjectを触った時に”触ったよ”という表示が出るようにします

mouse.cs
void OnTriggerStay2D(Collider2D coll){
        if (coll.gameObject.tag == "flower") {
                  Debug.Log ("触ったよ");
        }
  }

5、動かしたい画像に関連付ける

今作ったmouseというスクリプトを動かしたい方のObjectに関連付けます。

すると

触ったよ.mov.gif

このようにドラッグして動かして、当たり判定も出すことができます。

参考にしたサイト

6
5
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
6
5