V
V
vari0us2016-08-16 11:56:27
C++ / C#
vari0us, 2016-08-16 11:56:27

How to raycast a touch on a 2d object?

Hello community, please help.
Everything works with the mouse and everything is clear, but I can’t figure it out at all. I
’m doing a cross-platform demo (so far only PC and Android).
It is necessary to determine the game object on which the user taps the object by the wheelbarrow
- this is a 2d sprite with a 2d collider
. We need a working PS code
. RTFM did not find anything suitable all evening yesterday, this morning, too, at all.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
vari0us, 2016-08-19
@vari0us

It turns out that my code was still working. I was looking for a bug for three days, but it ended up in a different place.
I don't claim to be correct, this is how it works for me.

void OnGUI () {//Код проверялся в FixedUpdate, Update, OnGUI.OnGUI чтобы можно было проверить работу на устройстве, я не нашел как включить в плеере юнити эмуляцию тачей
    
    if (Input.touchCount > 0) {

      for(int i = 0; i < Input.touchCount; i++){
        //if (Input.touches [i].phase == TouchPhase.Stationary) {//Здесь можно выбрать фазу
        GUI.Label (new Rect(10,50,150,100), "Touch.pos.x=" + Input.touches [i].position.x.ToString());
        GUI.Label (new Rect(150,50,150,100), "Touch.pos.y=" +  ((float)Screen.height - Input.touches [i].position.y).ToString());//Ось Y перевернута "вверх ногами", решение (float)Screen.height - Input.touches [i].position.y

          Vector2 rayPos = new Vector2 (Camera.main.ScreenToWorldPoint (new Vector3(Input.touches [i].position.x, Input.touches [i].position.y, 0f)).x,Camera.main.ScreenToWorldPoint (new Vector3(Input.touches [i].position.x, Input.touches [i].position.y, 0f)).y);
          RaycastHit2D hit = Physics2D.Raycast (rayPos, Vector2.zero, 0f);
          if (hit) {
            //if(hit.transform.tag == "tag"){//Тег объекта по которому совершен тап
              transform.position = new Vector3(transform.position.x,transform.position.y+0.1f,transform.position.z);
              Debug.Log (hit.collider.name);
              GUI.Label (new Rect(10,30,100,100),hit.collider.name);
            //}
          }
        //}
      }

    }
  }

D
Denis Gaydak, 2016-08-17
@MrMureno

And now to the point.
Simple raycast - works with 3d colliders.
2D has its own physics and raycasts. something like:
var worldTouch = Camera.main.ScreenToWorldPoint(touch.Position);
var hit : RaycastHit2D;
hit = Physics2D.Raycast (Vector2(worldTouch.x,worldTouch.y),Vector2.zero, Mathf.Infinity);
read some documentation ;)

D
Daniil Basmanov, 2016-08-16
@BasmanovDaniil

Calculate world coordinates of the finger using Camera.ScreenToWorldPoint , pass to Physics2D.OverlapPoint , get Collider2D .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question