「Unity/Csharp/オブジェクトをドラッグ」の版間の差分
ナビゲーションに移動
検索に移動
編集の要約なし |
|||
| 1行目: | 1行目: | ||
==unity2020の場合== | ==unity2020の場合== | ||
<pre> | <pre> | ||
using UnityEngine.EventSystems; | using UnityEngine.EventSystems; | ||
| 22行目: | 22行目: | ||
} | } | ||
</pre> | </pre> | ||
上記は、以下の項目と違って、Colliderは不要。 | |||
==unity2019?== | ==unity2019?== | ||
unity2020だと以下は動作しなかったので・・ | unity2020だと以下は動作しなかったので・・ | ||
2020年10月5日 (月) 17:22時点における版
unity2020の場合
using UnityEngine.EventSystems;
public class BlockScript : MonoBehaviour, IDragHandler, IDropHandler
{
public void OnDrag(PointerEventData eventData)
{
Vector3 objectPointInScreen = Camera.main.WorldToScreenPoint(eventData.position);
Vector3 mousePointInScreen = new Vector3(Input.mousePosition.x,
Input.mousePosition.y,
objectPointInScreen.z);
Vector3 mousePointInWorld = Camera.main.ScreenToWorldPoint(mousePointInScreen);
mousePointInWorld.z = this.transform.position.z;
this.transform.position = mousePointInWorld;
}
public void OnDrop(PointerEventData eventData)
{
//Destroy(gameObject);
}
}
上記は、以下の項目と違って、Colliderは不要。
unity2019?
unity2020だと以下は動作しなかったので・・
画像オブジェクトにColliderをつけ以下コードをアタッチ(Add Component)するとドラッグでオブジェクトが動かせるようになる
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockScript : MonoBehaviour {
void Start () {
}
void Update () {
}
void OnMouseDrag()
{
Vector3 objectPointInScreen = Camera.main.WorldToScreenPoint(this.transform.position);
Vector3 mousePointInScreen = new Vector3(Input.mousePosition.x,
Input.mousePosition.y,
objectPointInScreen.z);
Vector3 mousePointInWorld = Camera.main.ScreenToWorldPoint(mousePointInScreen);
mousePointInWorld.z = this.transform.position.z;
this.transform.position = mousePointInWorld;
}
}