Unity obtaining Vector of click event

非 Y 不嫁゛ 提交于 2019-12-13 10:46:33

问题


I'm utilizing Unity's Vector3 method, ScreenToWorldPoint.

In short, I can click anywhere on a GameObject and obtain the Vector3 of where the click was in the game. However the result I'm obtaining is the Vector3 directly in front of the camera, rather then where I'm truly clicking on the surface of a given GameObject in the scene.

I want the coordinates of exactly where I click on the surface of a GameObject.


回答1:


You want to Raycast from the camera to the object. See the help pages for more Manual: Rays from the camera

using UnityEngine;
using System.Collections;

public class ExampleScript : MonoBehaviour {
    public Camera camera;

    void Start(){
        RaycastHit hit;
        Ray ray = camera.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit)) {
            Transform objectHit = hit.transform;

            // Do something with the object that was hit by the raycast.
        }
    }
}



回答2:


To obtain the Vector3 of exactly where you click on the surface of a GameObject utilize the following code:

    RaycastHit hit;
    Ray ray;
    Camera c = Camera.main;
    Vector3 hitPoint;


    Rect screenRect = new Rect(0, 0, Screen.width, Screen.height);
    if (screenRect.Contains(Input.mousePosition))
    {
        if (c != null)
        {
            ray = c.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                // If the raycast hit a GameObject...
                hitPoint = hit.point; //this is the point we want
            }

        }
    }

We create a ray from our mouse on screen and cast it into the world to calculate the exact position of where the mouse is in the scene.



来源:https://stackoverflow.com/questions/44663474/unity-obtaining-vector-of-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!