LoginSignup
9
5

More than 3 years have passed since last update.

Unityでオブジェクトをドラッグ&ドロップにあわせて動かす(2D)

Posted at

スプライトを追加する。
sprite.png

イメージをAssetに追加する。
dragdrop.png

スプライトにイメージを対応付ける。
settingimage.png

スプライトにBox Collider 2DをAdd Componentする。
collider.png

同様にスプライトにRigidbody 2DをAdd Componentする。

rigid.png

スプライトにスクリプトをAdd Componentする。
script_add.png

名前はNewBehaviourScriptのままでcreate addする。
script_name.png

作成されたスクリプトをダブルクリックしてvisual studioを立ち上げる。
open_script.png




以下のようなソースコードが書かれているので、それをアタッチする。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

↓ こんな感じ

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    // 追加
    private Vector3 screenPoint;
    private Vector3 offset;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    // 追加
    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;
    }
}

書き替えたらctrl + s で保存する。

※ ちなみにマウスカーソルの中央にイメージのセンター部分を持ってきたい場合はこのようにoffset分を消してやればよい。

Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenPoint);// + this.offset;

最後にRigidbody 2DのBody TypeをDynamicからKinematicに変更する(こうしないと重力でスプライトが落ちる)。
kinematic.png

これでドラッグ&ドロップでスプライトを動かすことができる。
result_draganddrop.png

追記

オブジェクトの位置は
transform.position
に格納されている。

参考

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