I'm attempting to implement drag and drop functionality in a 3d Unity environment using a camera with Perspective projection.
The following code should generate a ray from the current mouse (eventually, touch) position to the object that appears to be below the mouse on screen.
private Ray GenerateMouseRay()
{
Vector3 mousePositionFar = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.farClipPlane);
Vector3 mousePositionNear = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane);
Vector3 positionNear = Camera.main.ScreenToWorldPoint(mousePositionNear);
Vector3 positionFar = Camera.main.ScreenToWorldPoint(mousePositionFar);
Ray mouseRay = new Ray(positionNear, positionFar - positionNear);
return mouseRay;
}
In my Update method, when mouse activity is detected, I am printing the name and coordinates for the object the ray hits. Once I get the ray to cast correctly, I will be able to implement drag and drop functionality.
// Update is called once per frame
void Update()
{
//CalculatePosition();
if (Input.GetMouseButtonDown(0))
{
Ray mouseRay = GenerateMouseRay();
RaycastHit hit;
if(Physics.Raycast(mouseRay.origin, mouseRay.direction, out hit))
{
hitObject = hit.transform.gameObject;
objectPlane = new Plane(Camera.main.transform.forward * -1, hitObject.transform.position);
Debug.Log(hitObject.name);
Debug.Log(hitObject.transform.position.x + ", " + hitObject.transform.position.y + ", " + hitObject.transform.position.z);
}
}
}
Expected Output: Player 13.57, -8.5, 6.07
Actual Output: OceanWaterArea.5536325, -1.1, 1.218224
Any assistance is appreciated.
Solved by disabling collision on my water plane.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.