Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class TouchAndDrag : MonoBehaviour {
- public float speed = 10f;
- public Camera camera;
- bool hasTappedObject = false;
- void Update () {
- if (Input.touchCount > 0) { // if the user is touching the screen
- if (Input.GetTouch(0).phase == TouchPhase.Began) { // if it's an initial touch
- Vector2 worldPoint = Camera.main.ScreenToWorldPoint( Input.touches[0].position );
- RaycastHit2D hit = Physics2D.Raycast( worldPoint, Vector2.zero ); // cast a ray from the finger position into the scene
- if (hit != null && hit.collider != null) { // if the ray hits something
- Transform objectHit = hit.transform;
- 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)
- Debug.Log("Test");
- hasTappedObject = true; // set this variable to true
- }
- }
- } else if (Input.GetTouch(0).phase == TouchPhase.Moved) { // else it the user already has his finger on the screen and is moving it around
- if (hasTappedObject) { // if the user tapped the paddle
- Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition; // get the movement of the finger
- transform.Translate(0, touchDeltaPosition.y * speed, 0); // move the paddle object by the amount of the movement of the finger
- }
- } else if (Input.GetTouch(0).phase == TouchPhase.Ended) { // if the user lifts his finger from the screen
- hasTappedObject = false; // tell unity that he's not touching any object
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement