So I was searching for a code snippet for just moving a game object wherever I moved my finger without using raycasts and for my surprise there is none lol.
So here you go, just add this to a “FollowFinger.cs” script and attach it to any Game Object you want to move.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using UnityEngine; using System.Collections; public class FollowFinger : MonoBehaviour { private Vector3 screenPoint; private Vector3 offset; private float initialDepth = 0; void Start() { initialDepth = transform.position.z; } void Update () { if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { screenPoint = Camera.main.WorldToScreenPoint(transform.position); offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3( Input.touches[0].position.x, Input.touches[0].position.y, screenPoint.z)); } if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) { Vector3 curScreenPoint = new Vector3(Input.touches[0].position.x, Input.touches[0].position.y, screenPoint.z); Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint)+offset; curPosition.z = initialDepth; gameObject.transform.position = curPosition; } } } |