- Home /
Select and drag a gameObject with Touch
Hi, i'm developing my first game, and its a 2d game.
I need to select a square an drag it to collide another one, with a touch.
i just cant get it moving, i cant post my code cause i've tried so many things i would not know what to post.
also i think this might be so basic, but i've tried for hours and hours and cant gat that simple result.
detect touch, as i detected the touch then the gameobject on that position gets selected, and then drag it.
i've tried mainly with raycasting 2d, but have trouble every time, i'm so stuck at this point. i think i understand the principles of raycasting and raycast hit, but cant make it work.
PLEASE, I USE JAVASCRIPT!!!!! i've found more info in c# but it gets hardier to me to try things up.
Please help!
well for example i've tried this:
function Update () {
for (var touch : Touch in Input.touches){
var ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
var hit : RaycastHit2D;
if (Physics2D.Raycast (ray, hit)) {
//here i dont know how to select the gameObject that was hit
//so i can move it as i move the finger,it is maybe the collider?
collider2D.gameObject.transform.position = touch.position;
}
}
But in this part : if (Physics2D.Raycast (ray, hit))
I always get this error:
BCE0023: No appropriate version of 'UnityEngine.Physics2D.Raycast' for the argument list '(UnityEngine.Ray, UnityEngine.RaycastHit2D)' was found.
And dont know how to fix that.
Thanks a lot for your help!
Physics2D.Raycast doesn't have an overload like that from what the documentation says:
http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
The 3D version of the Physics class does however.
Answer by Aaeronn09 · Jun 09, 2014 at 08:16 AM
I think you can try delta position with touch..
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
This will calculate the touch by frames.. Try research on this. You havent posted the code so it wont be easy to say whats the problem.. If you can try posting the code..
Answer by Andres-Fernandez · Jun 09, 2014 at 06:55 AM
Maybe there's an easier way of doing it, but here's how I would do it:
First, set your sprite to a layer like "draggable" or similar. Second, attach a collider to it. Then use a raycast from the camera. Something like ViewportPointToRay, using the touch.position as the input, and check if that collides with the layer of your sprite. If it does, then you just need to set its position (every frame) based on the touch.position until you get the touch.phase == TouchPhase.Ended.
Your answer
Follow this Question
Related Questions
Raycasting UI elements - Without using Event Triggers 0 Answers
Raycast not working on touchscreen (Android tablet/phone) 2 Answers
Touch dont work 1 Answer
Make an Object follow your touch 0 Answers
Touch interface not working 1 Answer