i need help on touch script in unity

Updated on March 15, 2017 in Discussions
Share on Facebook0Tweet about this on Twitter0Share on Google+0Share on Reddit0
2 on March 15, 2017

hi guys
i want to shoot ball with touch (swipe) and i want touch zone   to  limit  only ball object .for detect ball i used raycast .when i  combine with script swipe doesn’t work .please help me .the following  is my script .

private RaycastHit hit;
private Ray ray;
private Vector3 footballPos;
private float Power =6f;
private float length = 0;
private bool SW = false;
private Vector3 final;
private Vector3 startpos;
private Vector3 endpos;

// Update is called once per frame
void Update ()
{

if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) {
ray = Camera.main.ScreenPointToRay (Input.GetTouch (0).position);
if (Physics.Raycast (ray, out hit)) {

// touchedobject = GameObject.Find (hit.transform.name);
Debug.Log (hit.transform.gameObject.tag);
if (hit.collider.name == “Ball”) {

print (“User tapped on game object ” + hit.collider.name);

final = Vector3.zero;
length = 0;
SW = false;
Vector2 touchDeltaPosition = Input.GetTouch (0).position;
startpos = new Vector3 (touchDeltaPosition.x, 0, touchDeltaPosition.y);

if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Moved) {
SW = true;
}

if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Canceled) {
SW = false;
}

if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Stationary) {
SW = false;
}
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Ended) {
if (SW) {
Vector2 touchPosition = Input.GetTouch (0).position;
endpos = new Vector3 (touchPosition.x, 0, touchPosition.y);
final = endpos – startpos;
length = final.magnitude;
GetComponent<Rigidbody> ().AddForce (final * Power);
}

}
}

}
}
}

  • Liked by
Reply
0 on March 15, 2017

Please don’t post the same question twice.

  • Liked by
Reply
Cancel
0 on March 15, 2017

I think you need to be a bit more specific about what you’re wanting and what you’re seeing. Just looking at code with little context is difficult. For example, can you get it to work with a mouse, but incorporating the touch code isn’t working as expected? Or, are you unable to have it detect the ball from the raycast? etc.
 
Where exactly are you having troubles?

  • Liked by
Reply
Cancel