0

How can I move an object (a gameobject fill color using GUITexture for example) by mouse click/touch to grid and check contains fill color for each tile?

If use Camera.main.ScreenToWorldPoint then can't check contains. Current my code to check contains work fine but gameobject not move with mouse :(

Link image: https://i.stack.imgur.com/f6gt6.png

My code is follow:

void OnMouseDown()
    {
        Vector2 mousePos = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
        transform.position = mousePos;
        Debug.Log("OnMouseDown: transform.position: " + transform.position);
    }
    void OnMouseDrag()
    {
        Vector2 mousePos = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
 
        transform.position = mousePos;
        Debug.Log("transform.position: " + transform.position);
 
        foreach (var x in GameBoard.Instance.listTileInGrid)
        {
            if (x.RectTile.Contains(mousePos))
            {
                Debug.Log("change color");
                x.ColorId = 1;
            }
        }
    }

Thanks in advance!

update:

i change:

transform.position = mousePos;

to

transform.guiTexture.transform.position = Camera.main.ScreenToViewportPoint(Input.mousePosition);
Community
  • 1
  • 1
691138
  • 97
  • 3
  • 8
  • 1
    The unity tag is reserved for Microsoft Unity. Please don't misuse it. – Lex Li Mar 14 '13 at 05:20
  • thank for reply, i have solved the problem at here: transform.guiTexture.transform.position = Camera.main.ScreenToViewportPoint(Input.mousePosition); http://answers.unity3d.com/questions/416536/moving-gameobjects-with-mouse-and-check-contains.html – 691138 Mar 14 '13 at 07:34
  • Please create an answer and mark it as answered then, so this question doesn't remain unanswered. – Joetjah Mar 14 '13 at 08:05
  • If you solved it yourself it would be great if you can write up your findings and solution as an answer so that others who face the same issue can see it too. – Flexo Mar 17 '13 at 20:13

1 Answers1

0

This is pretty simple. You can use the Vector3.Lerp function to achieve this. Use raycasting to get the mouse click position or the touch position. Then use the initial and the final position in the lerp function. The initial position being the position that the gameobject is at now and the final position being the click / touch position. You can find the article by The Game Contriver on the same here

Move to Touch / Click Position - The Game Contriver

gameOne
  • 609
  • 1
  • 10
  • 22