Raycast to mesh that stands on sphere

I have built a sphere with some meshes on it (islands).
When I click on any of the islands, I must generate an object at that exact point.

I have created this script to place an object at a point on the mesh:

void spawnObject (Vector3 position)
    {
        GameObject newCharacter = Instantiate(spawnCharacter, position, Quaternion.identity) as GameObject;
        Vector3 planetPosition = planet.transform.position;

        newCharacter.transform.parent = gameObject.transform;
        newCharacter.transform.LookAt(planetPosition);
        newCharacter.transform.Rotate(180, 0, 0);
    }

As you can see, I need to pass the click position to this function.
The trouble is that I don’t have experience with Raycast and I get some strange results.
How can I get the click position on those islands?

    protected virtual void Update() {
        /*
         * WARNING: DO NOT HARDCODE YOUR INPUTS
         *
         * If the mouse is pressed down Raycast into the world
         */
        if(Input.GetKeyDown(KeyCode.Mouse0)) {
            // How far do we raycast
            float distance = 100.0F;

            // The ray that will be cast
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            // Data Structure that holds information
            // about what we 'hit' with the Raycast
            RaycastHit hit;

            // Have we hit something?
            if (Physics.Raycast(ray, out hit, distance)) {
                // We hit something
                // RaycastHit gives us information
                Vector3 hitImpactPoint = hit.point; // World-Cooredinates
                Vector3 hitNormal = hit.normal; // The normal of the impact-point
                Collider hitCollider = hit.collider;
                GameObject hitGameObject = hit.collider.gameObject;
                float hitDistance = hit.distance;
            }
        }
    }

The above is an example of a Raycast. Please read the API and watch this video provided by Unity on Raycasting.

1 Like

In this area below is where you would want to instantiate and set the position. This is saying that we’re ever the raycast is being hit, so something

            if (Physics.Raycast(ray, out hit, distance)) {
                // We hit something
                // RaycastHit gives us information
                Vector3 hitImpactPoint = hit.point; // World-Cooredinates
                Vector3 hitNormal = hit.normal; // The normal of the impact-point
                Collider hitCollider = hit.collider;
                GameObject hitGameObject = hit.collider.gameObject;
                float hitDistance = hit.distance;
            }
        }
    }
1 Like