- Home /
How to snap a Prefab to the normal of an irregular mesh
Hi, I need to have a building follow the mouse, whist snapped to the surface of a low poly Icosphere. Im currently instantiating the prefab at the position of the mouse when hovering over the sphere (using raycasting) but the prefab seems to go crazy and fly towards the camera, rather than snapping to the face / normal of the mesh.
public GameObject objectPrefab;
private GameObject currentPrefab;
Ray ray;
RaycastHit hit;
// Update is called once per frame
void Update()
{
if (currentPrefab != null) {
CurrentPrefabMove ();
}
}
public void PlacePrefab(){
if (currentPrefab == null) {
currentPrefab = Instantiate (objectPrefab);
} else {
Destroy (currentPrefab);
}
}
private void CurrentPrefabMove(){
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
currentPrefab.transform.position = hit.point;
currentPrefab.transform.rotation = Quaternion.FromToRotation (Vector3.up, hit.normal);
}
}
This is the script which deals with that, any ideas?
Answer by exp3l3r_unity · May 06, 2020 at 06:52 PM
I figured it out! Just in case anyone got a similar problem of an object being instantiated at the mouse cursor and using raycasting to snap to an object - make sure to include a check that specifies the tag of the object youre trying to snap to or the raycast will hit the instantiated object, then change its position closer to the camera and then repeat.
Your answer
Follow this Question
Related Questions
How does the Triangles work on Mesh? 1 Answer
Is there a similar Command to lineRenderer.SetVertexCount for mesh?? 0 Answers
How do i access the MeshExtrusion.cs from Unity's PE? 1 Answer
How do i get the Raycast rotation? 1 Answer
How do i have a Vector3[] position be in another Vector3[] position (That Updates)?? 1 Answer