ドラッグ|Unity5

ドラッグ|Unity5

ドラッグ|Unity5 : ZIPファイル(507kb)

C#

Drag.cs

using UnityEngine;
using System.Collections;

public class Drag : MonoBehaviour {
	float offsetX;
	float offsetY;

	// Update is called once per frame
	void Update () {
		Vector2 tapPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
		Collider2D aCollider2d = Physics2D.OverlapPoint(tapPoint);

		if(Input.GetMouseButtonDown(0)){

			if (aCollider2d) {
				Vector2 mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
				Vector2 spritePos = transform.position;
				float dx = mousePos.x - spritePos.x;
				float dy = mousePos.y - spritePos.y;
				float rad = Mathf.Atan2 (dy, dx);
				float dist = Mathf.Sqrt (dx * dx + dy * dy);
				offsetX = Mathf.Cos (rad) * dist;
				offsetY = Mathf.Sin (rad) * dist;
			}
		}

		if(Input.GetMouseButton(0)){

			if (aCollider2d) {
				Vector2 mouseMovePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
				Vector2 sprite = transform.position;
				sprite.x = mouseMovePos.x - offsetX;
				sprite.y = mouseMovePos.y - offsetY;
				transform.position = sprite;
			}
		}

		if(Input.GetMouseButtonUp(0)){

		}
	}
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です