「Unity/Csharp/オブジェクトをドラッグ」の版間の差分
提供: 初心者エンジニアの簡易メモ
行1: | 行1: | ||
+ | ==unity2020の場合== | ||
+ | Collider不要。 | ||
+ | <pre> | ||
+ | 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); | ||
+ | } | ||
+ | } | ||
+ | </pre> | ||
+ | ==unity2019?== | ||
+ | unity2020だと以下は動作しなかったので・・ | ||
+ | |||
画像オブジェクトにColliderをつけ以下コードをアタッチ(Add Component)するとドラッグでオブジェクトが動かせるようになる | 画像オブジェクトにColliderをつけ以下コードをアタッチ(Add Component)するとドラッグでオブジェクトが動かせるようになる | ||
using System.Collections; | using System.Collections; |
2020年10月6日 (火) 02:22時点における版
unity2020の場合
Collider不要。
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); } }
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; } }