How to move in game 2D game object with mouse?
Hi there, I'm new to Unity and Game Dev, so just wanted to ask the basic question on how to move the game object with mouse movement. Something like pick an object (by clicking) and move it , then place it once the mouse click is released. Found few answers with 'camera.main.worldtoscreenpoint' but didn't understand them, I'll really appreciate if some one can also explain this 'camera.main.worldtoscreenpoint'.
thanks a lot :)
Answer by Veerababu.g · Mar 28, 2016 at 05:44 AM
bool IsPicked;
void Update(){
if(input.getmouseButtonUp(0)){
isPicked = false;
}
if(isPicked == true){
vector2 mousePos = camera.main.screentoWorldPoint(input.mousePosition);
transform.position = mousePos;
// if you want to smooth movement then lerp it
}
}
void OnMouseDown(){
isPicked = true;
}
Answer by Patri0t_Gamer · Mar 28, 2016 at 12:16 PM
hey thanks a lot,
with some minor changes in the code, its working. this is the final code - its for moving the object with mouse movement only (no click and drag)
using UnityEngine; using System.Collections;
public class MyMove : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = (pos);
}
}
Your answer
Follow this Question
Related Questions
Controller script active on both characters. 1 Answer
How do I create a 2D movement script that will cause prefabs to drift around the screen? 0 Answers
[Android] Character movement script help 1 Answer
Failed to create agent because it is not close enough to the NavMesh 4 Answers
TouchPad Help for Mobile 0 Answers