【Unity】ドラッグアンドドロップで3Dオブジェクトを動かす

投稿者: | 2020-10-30

ゲーム中にCubeをドラッグアンドドロップして同じ平面上を移動させてみます。

シーンには原点を通るPlaneオブジェクトとCubeを配置しています。

Cubeに他のオブジェクトとは違うタグを設定します。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class GameScript : MonoBehaviour
  6. {
  7.  
  8. Plane plane;
  9. bool isGrabbing;
  10. Transform cube;
  11.  
  12. // Start is called before the first frame update
  13. void Start()
  14. {
  15. plane = new Plane(Vector3.up, Vector3.up);
  16. }
  17.  
  18. // Update is called once per frame
  19. void Update()
  20. {
  21. if(Input.GetMouseButtonDown(0))
  22. {
  23. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  24.  
  25. RaycastHit hit;
  26. if(Physics.Raycast(ray,out hit, Mathf.Infinity))
  27. {
  28. if (hit.collider.tag == "Player")
  29. {
  30. isGrabbing = true;
  31. cube = hit.transform;
  32. }
  33. }
  34. }
  35.  
  36.  
  37. if (isGrabbing)
  38. {
  39. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  40. float rayDistance;
  41. plane.Raycast(ray, out rayDistance);
  42.  
  43. cube.position = ray.GetPoint(rayDistance);
  44.  
  45. if (Input.GetMouseButtonUp(0))
  46. {
  47. isGrabbing = false;
  48. }
  49. }
  50.  
  51. }
  52.  
  53. }

スクリプトではStart()で、真上を向いて、原点の1メートル上(0, 1, 0)にPlaneを作ります。これは3DオブジェクトのPlaneとは違って見えません。

  1. plane = new Plane(Vector3.up, Vector3.up);

マウス左クリックで、カーソルからカメラの向いている方向へレイを飛ばします。タグを使ってCubeかどうかを調べて、Cubeなら掴みます。

  1. if(Input.GetMouseButtonDown(0))
  2. {
  3. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // カーソルからのレイ
  4.  
  5. RaycastHit hit;
  6. if(Physics.Raycast(ray,out hit, Mathf.Infinity)) // レイを飛ばす
  7. {
  8. if (hit.collider.tag == "Player") // タグで見分ける
  9. {
  10. isGrabbing = true; // 掴む
  11. cube = hit.transform; // Cubeを保存
  12. }
  13. }
  14. }

そして、Cubeを掴んでいる間は、同じ様にレイを飛ばして、Start()で作ったPlaneとレイとの交点にCubeを移動し続けます。

  1. if (isGrabbing)
  2. {
  3. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // レイ
  4. float rayDistance;
  5. plane.Raycast(ray, out rayDistance); // Planeにレイを飛ばす
  6.  
  7. cube.position = ray.GetPoint(rayDistance); // レイが当たった位置
  8.  
  9. if (Input.GetMouseButtonUp(0))
  10. {
  11. isGrabbing = false;
  12. }
  13. }

このときはPhysics.RaycastでなくPlane.Raycastを使います。Plane.Raycastでは交点までのレイの距離だけがわかります。レイのGetPoint()メソッドを使うと、引数に渡した長さだけレイが進んだ場所の座標がわかるので、Cubeの位置にこれを代入します。

左クリックを離すと掴むのをやめます。

この方法だと、Cubeをクリックした時にPlaneとの交点まで瞬時に動きます。

コメントを残す

メールアドレスが公開されることはありません。