1
\$\begingroup\$

In my Unity3d game, I want to get the world position that was touched, when I touch a specific object, regardless of all objects that are in front of it.

How would I do that, I only know Camera.ScreenPointToRay(...), but for some reason that does not work properly?


OK - one cannot answer the question with the information I provided.

In order to determin the point, where the Ray hit the object, I used RaycastHit.transform.position (which refers to the Transform object that was hit) as opposed to RaycastHit.point (which refers to the Vector3 in world space, where the RaycastHit happened).

\$\endgroup\$
1
\$\begingroup\$

I've worked out a system that prints the position the mouse is hovering over. You will probably want to write a function that doesn't update every frame. When you click it spits out an Vector3 of the position in worldspace you are hovering over with your mouse in Screen space.

using UnityEngine;
using System.Collections;

public class check : MonoBehaviour
{
    void Update()
    {
        RaycastHit hit;
        // Cast a ray from the mouse position to the world
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //When the ray hits anything, print the world position of what the ray hits using hit.point
        if (Physics.Raycast(ray, out hit)  && Input.GetMouseButtonDown(0)))
            print(hit.point);
    }
}

You can now Instantiate GameObjects with Instantiate(yourGO,hit.point,Quaternion.identity);

\$\endgroup\$
2
\$\begingroup\$

Camera.ViewportToWorldPoint allows you to get the place you clicked on the screen as a point in world space.

\$\endgroup\$
  • \$\begingroup\$ Thanks, but I have a different problem. I tried to spawn objects where I click, but they only get spawned at one position (where the camera was at the start of the scene) Might this be a problem with UI? \$\endgroup\$ – 000000000000000000000 Apr 11 '16 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.