Finger Swipe on Object
I have a sphere that I'm trying to move by swiping my finger across the screen, but I'm unable to figure it out. Any thoughts? I can't get the sphere (called Ball) to move. I'm brand new to Unity, but here's what I have so far:
using UnityEngine; using System.Collections;
public class BallMover : MonoBehaviour{
 private Vector2 startPos;
 private Vector2 endPos;
 private Vector2 touchPos;
 private Rigidbody rb;
 private Touch touch;
 void Start(){
     rb = GetComponent<Rigidbody> ();
 }
 void FixedUpdate ()
 {
     float speed = Time.time;
     float moveHorizontal;
     float moveVertical;
     // Check if user touches screen
     if (touch.phase == TouchPhase.Began)
     {
         // get the x and y coordinates of screen touch
         startPos = touch.position;
         endPos = touch.position;
         // set movement to 0
         moveHorizontal = 0.0f;
         moveVertical = 0.0f;
     }
     // Check if user removes finger from screen
     if (touch.phase == TouchPhase.Ended)
     {
         // get last finger touch coordinates
         endPos = touch.position;
         // record time it took to finish finger swipe
         //speed = Time.time - speed;
         // set movement to end touch minus begin touch for both x and y axis
         moveHorizontal = endPos.x - startPos.x;
         moveVertical = endPos.y - startPos.y;
         // create movement variable
         Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
         // add force to object
         rb.AddForce(movement * speed);
     }
 }
}
Answer by jep7 · Sep 08, 2015 at 06:37 PM
You have declared a variable 'touch' and you are dealing with it a lot, but you didn't define it! At least you have to add this to your FixedUpdate():
 FixedUpdate(){
     if(Input.touches.Length > 0){
         touch = Input.touches[0];
         
         //put your code inside the FixedUpdate() here
     }
 }
Your answer
 
 
             Follow this Question
Related Questions
Player follow touch when holding down your finger on the screen (C#) 1 Answer
How to enable the script after clicking the mouse/touch?^ 1 Answer
C# Touch Input with Raycast on Interactive Map to toggle Canvas 0 Answers
OnScreen-Stick that moves to the position touched 0 Answers
how to simulate a hand using IMUs ? 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                