Search Unity

Move gameObject (main player) by clicking on another UI object

Discussion in 'Getting Started' started by dzaiats, Jan 21, 2015.

  1. dzaiats

    dzaiats

    Joined:
    Jan 21, 2015
    Posts:
    6
    Hello,
    I cannot find solution. Please, help me.
    I want to move my main game object (main character) by clicking on arrows (Up, Down, Left, Right) which is UI object on the screen. I was trying a lot of variant how to do it but everything was wrong. For example:
    I created C# Script and attached it to the object "arrowUp"

    void Update() {
    if ((Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) || (Input.GetMouseButton(0)))
    {
    player = GameObject.FindGameObjectWithTag("Player");
    player.rigidbody2D.AddForce(newVector2(0,100));
    Debug.Log("Top");
    }
    }

    How to solve it? Please, help!
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    5,431
  3. dzaiats

    dzaiats

    Joined:
    Jan 21, 2015
    Posts:
    6
  4. dzaiats

    dzaiats

    Joined:
    Jan 21, 2015
    Posts:
    6
  5. dzaiats

    dzaiats

    Joined:
    Jan 21, 2015
    Posts:
    6
    I found answer. Need to use correct collider. I was using Circle collider, but need to use Sphere.
    Finally C# code is:
    RaycastHithit;
    Code (CSharp):
    1. RaycastHit hit;
    2.         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    3.         if ((Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown(0)))
    4.         {
    5.             if (Physics.Raycast(ray, out hit)) {
    6.                 if (hit.transform.tag == "arrow_bottom" )
    7.                     Debug.Log( "Bottom");
    8.             }
    9.         }
     
  6. DustyMcp

    DustyMcp

    Joined:
    May 23, 2013
    Posts:
    25
    I dont see how raycasting have much to do with the question but use Vector3.MoveTowards on objects.