-2
\$\begingroup\$

My code here works with a keyboard:

if (Input.GetKeyDown (KeyCode.UpArrow)) {
  if (transform.position.y < 1.662f) {
    transform.Translate (0, 0.26F, 0);
  }
}

if (Input.GetKeyDown (KeyCode.DownArrow)) {
  if (transform.position.y > 1.142f) {
    transform.Translate (0, -0.26F, 0); 
  }
}


if (Input.GetKeyDown (KeyCode.RightArrow)) {
  if (transform.position.x < 3.681f) {
    transform.Translate (0.46f, 0, 0);
  }
}

if (Input.GetKeyDown (KeyCode.LeftArrow)) {
  if (transform.position.x > 3.221f) {
    transform.Translate (-0.46f, 0, 0);
  }
}

How could I transform it so that it works as touch input?

\$\endgroup\$
  • \$\begingroup\$ I'm not used to Unity for mobile (actually I've never used it). BUT I think you need to: possibility one: create buttons in your interface so the player can press. Or possibility two: use Input.GetTouch and Touch.position and verify the results and relate to the position in the screen. \$\endgroup\$ – Arthur 'Gibraltar' Condino Jan 13 '17 at 2:26
  • 2
    \$\begingroup\$ Or alternatively, use the mobile input script that comes with the standard assets package. \$\endgroup\$ – Gnemlock Jan 13 '17 at 3:22
-1
\$\begingroup\$

Lets say you have a virtual joystick with 4 buttons arranged like 'wasd' keys with names 'up','down','left','right'. Now, do this:

if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
 Ray ray = Camera.ScreenPointToRay(Input.GetTouch(0).position);
 RayCastHit hit;
 if(Physics.Raycast(ray, out hit)
 {
  if (hit.gameObject.name == "up" && transform.position.y < 1.662f)
  {
   transform.Translate (0, 0.26F, 0);
  } 
  else if (hit.gameObject.name == "down" && transform.position.y > 1.142f)
  {
   transform.Translate (0, -0.26F, 0);
  }
  else if (hit.gameObject.name == "left" && transform.position.x > 3.221f)
  {
    transform.Translate (-0.46f, 0, 0);
  }
  else if (hit.gameObject.name == "right" && transform.position.x < 3.681f)
  {
    transform.Translate (0.46f, 0, 0);
  }
}}

Hope this helps :)

\$\endgroup\$
  • \$\begingroup\$ hi Geo Baby ,thanks for your help but when i tried your code , it show an error 'UnityEngine.RaycastHit' does not contain a definition for 'gameObject' \$\endgroup\$ – Farouk Douglas Jan 13 '17 at 13:54
  • \$\begingroup\$ Hi Farouk, try hit.collider.tag or hit.collider.name or hit.collider.gameObject.name. \$\endgroup\$ – Geo Baby Jan 13 '17 at 19:07
  • \$\begingroup\$ It seems you could have easily looked this up in the API instead of guessing, and providing incorrect code. Your example accesses RayCastHit.GameObject; RayCastHit does not exist, and RaycastHit does not contain a game object reference. \$\endgroup\$ – Gnemlock Jan 13 '17 at 19:20

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.