touch place

Basically i am trying to place an object with touch phase began and while holding touch down moving touch in any direction and when touch phase is ended or cancelled it will add force in the form of a vector p2-p1. I am not much of a coder and know my problem is within the update. Any suggestions would be great.

Here is the code:

var rubberband : Rigidbody;

var rubberend : Transform;

private var touchstart : Vector3;

private var touchend : Vector3;

private var wasHit : boolean = false;

function Update()

{

if(wasHit == true)

{

//print(“I’m Close”);

rubberband.rigidbody.AddForce (touchend - touchstart * 200);

}

else if(Input.touchCount > 0)

{

wasHit = false;

var touch : Touch = Input.touches[0];

if(touch.phase == TouchPhase.Began)

{



 touchstart = touch.position;

 PlaceBand();

 }

 if(touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)

 {

 touchend = touch.position;

 LaunchBand();

 

 }

}

}

function PlaceBand()

{

var p1 = Camera.main.ScreenPointToRay (touchstart);

var hit : RaycastHit;

if (Physics.Raycast (p1,hit,100))

{

if (hit.collider.gameObject.tag == “test”)

{

Instantiate(rubberband,hit.point,rubberband.rotation);

}

}

}

function LaunchBand()

{

var p2 = Camera.main.ScreenPointToRay (touchend);

var hit : RaycastHit;

if (Physics.Raycast (p2,hit,100))

{

if (hit.collider.gameObject.tag == “test”)

{

Instantiate(rubberend,hit.point,rubberband.rotation);

wasHit = true;

}

}

}

Have you considered using an external library for gesture detection? I can recommend Input Touches.

It (and other gesture libraries, although I cannot vouch for them) can do all the work for you, so a situation like you are describing will become one or two lines of code for you:

  1. Register to get an event whenever a swipe or drag occurred, and;
  2. Handle the event in your own method, while receiving the force or direction from the library, depending on the event.

Another advantage to this approach is that it is cross device, as Input Touches handles mouse and touch events simultaneously.