Mark Zareal
Mark Zareal

Reputation: 23

How to drag gameObject using touch(unity2d)

I searched this on the internet but I still haven't found the answer I wanted.

So, I have a 2d tiled game and each tiles position is a multiple of 1.25 for example 7.5, 3.75. There is going to be a player walking on top it and i want to control the player by dragging it and if you release the touch it would be perfectly on a tile instead of in between the tiles. Right now, I can't even figure out how to drag the gameObject with touch. Can anyone help me and explain to me how to do that?

Upvotes: 1

Views: 306

Answers (1)

axwcode
axwcode

Reputation: 7824

You need to have a collider on every object you plan to move. Then create a class whose sole purpose is to fire a Raycast. Detect when a touch happens. Then fire the Raycast.

RaycastHit hit;
if(Physics.Raycast(ray, out hit, 100))
    Debug.DrawLine(ray.origin, hit.point);

You will notice that you have what you hit; with that you can send a message to that particular object.

hit.collider.SendMessage("move");

Inside the object that you hit, you now have to use the coordinates of the touch position to update the transform.position.

Upvotes: 1

Related Questions