Hi, I want to move object to new position of mouseCoursor,
for example the object is on the floor and i want to move it along the floor and the corsor
so the raycast should hit colider at mouse position, how can I do it? i tried like 20 options, nothing works
if (Input.GetMouseButtonDown (0)) {
RaycastHit hit;
Ray toMouse = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (toMouse,out hit)){
wheretoGo.transform.position = new Vector3 (hit.point.x,hit.point.y,hit.point.z);
Debug.DrawRay (toMouse.origin, toMouse.direction*1000, Color.yellow);
this above does not work:( it moves objects to a different possition then mouse couror
I just added an object with a collider and stretched it across the screenspace several units behind the object and in front of the camera.
Click anywhere in front of that screen ( and using a distance parameter to the raycast ) it worked every time.
It works similarly with a plane, as long as you click somewhere in the direction of the plane but within the distance being tested. Although the object I moved kept going through the object.
However, you could also try turning off the renderer so that it is only used for raycasting. You may also have to tell the raycast to work with triggers so that you can set the collider to a trigger so it can be moved through as needed.
Read up on the raycast documentation as that has quite a bit of information.
like Xrystal said, you need to hit a collider in order to get hit info back from the ray.
but as you say “… floor…” you can do this:
if (Input.GetMouseButtonDown (0))
{
RaycastHit hit;
Ray toMouse = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast(toMouse, out hit, Mathf.Infinity, 1 << LayerMask.NameToLayer("Ground")))
{
transform.position = new Vector3 (hit.point.x,transform.position.y,hit.point.z);
Debug.DrawRay (toMouse.origin, toMouse.direction*1000, Color.yellow);
}
}
1 << LayerMask.NameToLayer(“Ground”) makes the ray only cast against everything in the layer “Ground”
also changed transform.position = new Vector3 (hit.point.x,transform.position.y,hit.point.z);
as i assume that you want to move the object the script is on and you don’t want to use the hit.point.y but the y the object has.