- Home /
Raycast object flies towards mouse on screen, i need it on floor
I am trying to raycast a "cursor" object on to the terrain below from the camera using the mouse's position, but for some reason the object I am raycasting is flying towards the mouse and not staying on the ground.
Here is my code:
public Camera MainCam;
void Update () {
//pointCursor
RaycastHit hit;
Ray ray = MainCam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
transform.position = hit.point;
}
}
UPDATE: FIXED, just needed to add a layermask
Hi, do you $$anonymous$$d showing me how you use layermask to solve the problem? I'm having it too
Add a layer and apply it to the object the ray will cast on, and apply it in the Unity inspector as well.
public LayerMask meshLayer;
....
if (Physics.Raycast(ray, out hit, 1000, meshLayer)){
...
}
Answer by victorbisaev · Jan 28, 2018 at 11:57 PM
If the "hit.point" is closer to the camera than "transform.position" then it moves the object closer to the camera with every "Update" if the object is successfully raycasted because of "transform.position = hit.point".