- Home /
Move 2d game object instantly on position of Touch Input.
I have a 2d game object (a rectangle) that i want to move on touch input based on the position of the users touch. With the following code i observe that the position of the Player(1) do change with my touch Input but as soon as i touch on the screen (my first touch) the player disappears and all i can do is see it's position changing in the editor while i touch the screen :/. Any help?
PS : I'm new to Unity.
Code :
using UnityEngine;
using System.Collections;
public class TouchTest : MonoBehaviour {
// Use this for initialization
private Rigidbody2D myrigidBody;
void Start () {
myrigidBody = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update () {
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) {
Debug.Log (Input.GetTouch(0).position);
myrigidBody.transform.position = new Vector3 (Input.GetTouch(0).position.x,Input.GetTouch(0).position.y);
}
}
}
Answer by Aggerwal · Jun 26, 2016 at 08:59 PM
I had the same problem as you did and I finally figured it out a few weeks ago. to put it simple, when you touch the phone screen, the coordinates you get when the debug runs are the pixel coordinates of the phone screen but unity is working with units. So obviously when you set the position of the player to a couple of hundred units, it goes far away from the actual game space in unity. You can just convert the pixel position to world position that Unity uses. But before we get to that let me tell you some other things. Getting a reference to a rigidbody component is really useless if you just want to change the position. So instead, since the change in position code is on the object itself, you could just say: this.transform.position
And another thing, since you are using 2D position, you should use the Vector2 instead since Z axis isn't even being used. Now to change from pixel coords to unity units coords you could say something like this: Vector 2 touchPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position
When you debug the touchPos variable you will see the they are much smaller and you will see the player now :)
Your answer
Follow this Question
Related Questions
Fast touch control and precise aiming 0 Answers
Trying to get the player to face the direction of a touch 1 Answer
Stop Moving When Not Touching Screen? 1 Answer
Split screen in half - Touch Controls 3 Answers
I Need Help With Mobile Touch Movement. 0 Answers