1. 程式人生 > >Unity3D 入門小技巧——滑鼠拾取並移動物體

Unity3D 入門小技巧——滑鼠拾取並移動物體

一、滑鼠拾取物體的原理

Unity3D當中,想要在觀察面(Aspect)中拾取物體(有碰撞屬性)的方法一般如下:

1、宣告一個觀察的攝像機、一個從攝像機原點出發的射線Ray以及一個用於檢測碰撞的RaycastHit;

2、將射線Ray定義為從攝像機原點出發並且指向當前滑鼠所在的座標(螢幕座標);

3、定義碰撞RaycastHit為射線Ray與有碰撞屬性的物體的碰撞點。

具體程式碼實現如下(C#程式碼):

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

public class camera : MonoBehaviour
{
    public Camera ca;
    private Ray ra;
    private RaycastHit hit;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
            ra = ca.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ra, out hit))
            {  
                     
            }
    }
}
應用一:當滑鼠按住不動時,移動被選定物體隨滑鼠一起移動
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class camera : MonoBehaviour
{
    public Camera ca;
    private Ray ra;
    private RaycastHit hit;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            ra = ca.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ra, out hit))
            {
                hit.collider.gameObject.transform.position = ca.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, hit.collider.gameObject.transform.position.z));
            }
        }
    }
}
應用二:當滑鼠點選物體時,物體隨滑鼠一起移動;當滑鼠再次點選時,放下物體。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class camera : MonoBehaviour {
    public Camera ca;
    private Ray ra;
    private RaycastHit hit;
    private int flag = 0;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            ra = ca.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ra, out hit))
            {
               if (flag == 0)
                {
                    flag = 1;
                } else
                {
                    flag = 0;
                }
            }
        }
        if (flag == 1)
        {
            hit.collider.gameObject.transform.position = ca.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, hit.collider.gameObject.transform.position.z));
        }

	}
}