0
\$\begingroup\$

I want to detect the hexagonal tile a unit is on upon clicking on the unit. I was thinking of using a ray cast I can't get it to work.

I'm trying to get the raycast to shoot from the bottom of the unit and change the material of the collided object.

if (Input.GetMouseButtonDown (0)) {

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if(Physics.Raycast(ray, out hit)){

        Debug.Log (hit);

        string hitTag = hit.transform.tag;

        if(hitTag == "player"){

            if(Physics.Raycast(user.transform.position,Vector3.down,10)){

                Debug.Log ("I'm on something!");

                hit.collider.renderer.material.color = Color.red;

            }
        }
    }
}

What might be going wrong?

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

If in general clicking the unit has no other use than selecting the tile, you could simply put the units on the Ignore Raycast layer so you can select directly the tile, in this case you can also attach a script on the tiles with the OnMouseDown function. If you want to access, in that way, the unit, you could maintaing of structure describing the tiles (so also where are the units) and update it when necessary.

I'm not sure what user is in your code, but I think that you can create a vector like:

Vector3 rayStartPoint = new Vector3(user.tranform.position.x, -5, user.transform.position.z)

(assuming that everything at -5 y is under the field) and then:

Physics.Raycast(rayStartPoint, Vector3.up, 10).

I think your tiles are on a field so, also in this case, you have to set the field layer on Ignore Raycast otherwise the first thing to be hit will be the field.

If you want to use only a single raycast you could just set all your tiles to a specific layer and then make so that the raycast hits only that layer, for that specific operation:

Physics.Raycast(ray, out hit, layerMask)

Layers

\$\endgroup\$
0
\$\begingroup\$

You are performing two raycasts, but only storing the result of the first one in hit. So the renderer you access to change material color to red is the renderer of the player, not the renderer of the tile.

Add 'out hit' as a parameter to your second Physics.Raycast call:

Physics.Raycast(user.transform.position,Vector3.down, out hit, 10);
\$\endgroup\$

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.