Advertisement
Guest User

Untitled

a guest
May 3rd, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class TouchAndDrag : MonoBehaviour {
  5.     public float speed = 10f;
  6.     public Camera camera;
  7.     bool hasTappedObject = false;
  8.  
  9.     void Update () {
  10.         if (Input.touchCount > 0) { // if the user is touching the screen
  11.             if (Input.GetTouch(0).phase == TouchPhase.Began) { // if it's an initial touch
  12.                 Vector2 worldPoint = Camera.main.ScreenToWorldPoint( Input.touches[0].position );
  13.                 RaycastHit2D hit = Physics2D.Raycast( worldPoint, Vector2.zero ); // cast a ray from the finger position into the scene
  14.                 if (hit != null && hit.collider != null) { // if the ray hits something
  15.                     Transform objectHit = hit.transform;
  16.                     if (objectHit.tag == "Paddle") { // if the object hit is tagged as "paddle" (you could use name or any other parameter here, I just want to be sure the user is tapping the right thing)
  17.                         Debug.Log("Test");
  18.                         hasTappedObject = true; // set this variable to true
  19.                     }
  20.                 }
  21.             } else if (Input.GetTouch(0).phase == TouchPhase.Moved) { // else it the user already has his finger on the screen and is moving it around
  22.                 if (hasTappedObject) { // if the user tapped the paddle
  23.                     Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition; // get the movement of the finger
  24.                     transform.Translate(0, touchDeltaPosition.y * speed, 0);     // move the paddle object by the amount of the movement of the finger
  25.                 }
  26.             } else if (Input.GetTouch(0).phase == TouchPhase.Ended) { // if the user lifts his finger from the screen
  27.                 hasTappedObject = false; // tell unity that he's not touching any object
  28.             }
  29.         }
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement