Unity obtaining Vector of click event

2019-09-22 10:36发布

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.

2条回答
Summer. ? 凉城
2楼-- · 2019-09-22 11:06

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.

查看更多
【Aperson】
3楼-- · 2019-09-22 11:18

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.
        }
    }
}
查看更多
登录 后发表回答