- Home /
Moving object to position of finger at screen
Hi. I am trying to make in-game object to move with some speed around the screen. I want to controll it by moving my finger. Start position of object is x=0 y= 0 z=0 in world and in the middle of a screen. I want object to follow my finger. I created UI image and I wanna use Vector to directions(I think it s best and easiest way, if there's another show me). My C# script attached to image:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class Kontroler : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler {
public float smoothing;
private Vector2 origin;
private Vector2 direction;
private Vector2 smoothDirection;
public Text tekst;
void Awake () {
direction = Vector2.zero;
}
public void OnPointerDown (PointerEventData data) {
tekst.text="Pointer down";
origin = data.position;
}
public void OnDrag (PointerEventData data) {
tekst.text="Pointer drag";
Debug.Log(data.position);
Vector2 currentPosition = data.position;
Vector2 directionRaw = currentPosition - origin;
direction = directionRaw.normalized;
}
public void OnPointerUp (PointerEventData data) {
tekst.text="Pointer up";
direction = Vector3.zero;
}
public Vector2 GetDirection () {
smoothDirection = Vector2.MoveTowards (smoothDirection, direction, smoothing);
return smoothDirection;
}
}
And script attached to object:
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour
{
public float speed;
public Kontroler panel;
void Update ()
{
Vector2 direction = panel.GetDirection ();
Vector3 movement = new Vector3 (direction.x, 0.0f, direction.y);
GetComponent<Rigidbody>().velocity = movement * speed;
}
}
I am making this project for Android.
Answer by hosain · Aug 07, 2015 at 11:25 AM
https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/mobile-development i think this vedio is very useful
Your answer
Follow this Question
Related Questions
How to make camera position relative to a specific target. 1 Answer
Problem on new InputSystem touch(UI) 1 Answer
how use specific for mobile button when we have 3 ? 1 Answer
Multiple Cars not working 1 Answer
Touchscreen car controls 2 Answers