Can anyone tell me why this does not work? Every time I click on the cube object that this script is attached to, the sphere object (placedObject) is placed in the same spot. Shouldn’t it be placed differently if I click on different screen coordinates? What am I doing wrong here? Any help would be appreciated, thanks.
using UnityEngine;
using System.Collections;
public class TestScreenToWorldPoint : MonoBehaviour {
public GameObject placedObject;
void OnMouseDown()
{
Vector3 p = GetPlacementPoint(Input.mousePosition.x, Input.mousePosition.y);
placedObject.transform.position = p;
}
private Vector3 GetPlacementPoint(float x, float y)
{
Vector3 screenPoint = new Vector3(x,y, 0f);
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(screenPoint);
worldPoint.z = transform.position.z + .5f;
return worldPoint;
}
}
ScreenToWorldPoint uses the Z coordinate of its parameter to determine how far away from the camera to put the new object. If it’s 0 (and it is in your example), you will always get back the camera’s own position.
There are few instances where you want to use ScreenToWorldPoint. Instead, try ScreenPointToRay and raycasting to the object, and use hit.point to determine the placement position.
Bless you!
This worked exactly as I wished!
using UnityEngine;
using System.Collections;
public class TestScreenToWorldPoint : MonoBehaviour {
public GameObject placedObject;
void OnMouseDown()
{
Vector3 p = GetPlacementPoint(Input.mousePosition.x, Input.mousePosition.y);
placedObject.transform.position = p;
}
private Vector3 GetPlacementPoint(float x, float y)
{
Vector3 screenPoint = new Vector3(x,y, 0f);
Ray ray = Camera.main.ScreenPointToRay(screenPoint);
RaycastHit hit;
if (Physics.Raycast (Camera.main.transform.position, ray.direction, out hit))
{
return hit.point;
}
else
{
return Vector3.zero; //this shouldn't happen
}
}
}