x


Casting a ray to detect the touched object in world space does not work

I am trying to determine the object that I touch on the iPhone by casting a ray from the camera position to the touched position on the screen. It does not work. When I dray the ray as a Gizmo, I can see the ray moving outside the game region and also into opposite directions as if the scale and orientation are wrong. What am I doing wrong? Below is the script:

function OnDrawGizmos(){
        Gizmos.color = Color.blue;
        var touch : iPhoneTouch;
        if (iPhoneInput.touchCount > 0) {
            touch = iPhoneInput.GetTouch(0);
            pos = touch.position;
            var ray : Ray = Camera.main.ScreenPointToRay(Vector3(touch.position.x, touch.position.y));
            var hit : RaycastHit;
            if (Physics.Raycast(ray,hit))
            {
                Gizmos.DrawCube (hit.point, Vector3(1,1,1));
            }

            Gizmos.DrawRay (ray.origin, ray.direction * 100);
        }   
    }
more ▼

asked Jun 07 '10 at 03:09 PM

Serve_Hermans gravatar image

Serve_Hermans
186 5 5 13

(comments are locked)
10|3000 characters needed characters left

3 answers: sort voted first

Try using Input.mousePosition instead of getting the position of the touch. If that works, then you know that it's a coordinate system error. ScreenPointToRay and Input.mousePosition both assume (0,0) is in the bottom left. I don't know off the top of my head what iPhoneTouch.position uses.

more ▼

answered Jun 07 '10 at 03:58 PM

Tetrad gravatar image

Tetrad
7.2k 27 37 89

(comments are locked)
10|3000 characters needed characters left

Check this one out, might find it useful:

http://www.youtube.com/watch?v=oOfPMKdJdKk

more ▼

answered Jun 21 '11 at 01:12 AM

revelopment gravatar image

revelopment
61 1 1 1

(comments are locked)
10|3000 characters needed characters left

I think it's because you're using a Vector3 instead of a Vector2:

        var ray : Ray = Camera.main.ScreenPointToRay(Vector3(touch.position.x, touch.position.y));

should be:

        var ray : Ray = Camera.main.ScreenPointToRay(Vector2(touch.position.x, touch.position.y));
more ▼

answered May 17 '12 at 10:21 AM

shaystibelman gravatar image

shaystibelman
242 11 15 21

or just add the 3rd vector direction (z)

Jun 05 '12 at 07:04 AM shaystibelman
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2000
x1531
x580

asked: Jun 07 '10 at 03:09 PM

Seen: 3369 times

Last Updated: Jun 05 '12 at 07:04 AM