- Home /
Dragging an Object with mouse in 2D
i want to drag a paddle in my game with mouse.I want game object to be dragged with mouse.The object is meant to be moved in y-axis only.Any help would be really appreciated.
Answer by NoseKills · Apr 22, 2014 at 06:56 PM
Something like this in an Update method of your Game class:
// convert the touched screen position to 3D world position
// Vector3 touchPos = Camera.main.ScreenToWorldPoint(Input.touches[0].position); // when using touch
Vector3 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); // when using mouse
// get the current position of the paddle GameObject or whatever you want to move
Vector3 originalPaddlePos = paddleGameObject.transform.position;
// replace the y coordinate with the y of touched pos.
originalPaddlePos.y = touchPos.y;
// set the paddle position to the modified one
paddleGameObject.transform.position = originalPaddlePos;
If you're using a physics engine you might want to move the paddle by applying forces to it rather than just moving it. Moving it might cause strange issues as you might just tell the paddle to move on top of the ball during 1 frame etc.
although i marked it as answer but this script is causing problems.$$anonymous$$y gameObject seems to run towards left of screen and it stays there no matter where i touch.can you please tell why this is happening?
How are your axis and camera set up ? Do you know which axis "left" is and is it negative or positive ?