- Home /
Moving object with mouse, without clicking
im making a city building game, and i want to make it like other city building games where you have a blueprint of the building at first and when you click it makes the building. im doing this by making an object that will act like the blueprint, that will move with the mouse, and when you leftclick it will selfdestroy and instantiate the building at its position. i've made this code in C#, with some help from other threds on this forum:
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint)+offset;
transform.position = curPosition;
}
as you can see it only work when i hold and drag the mouse. i've tried putting both codes into one update function but it won't work. please help.
sorry for the long text and thank you very much for your time.
Answer by robertbu · May 04, 2014 at 02:42 PM
I believe you are looking for OnMouseOver():
http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.OnMouseOver.html
Answer by Deadpanda · May 04, 2014 at 03:30 PM
Thank you for your answer :) i tried it out and realised something.. i forgot a Start function and that's why my Update didn't work... my code looks like this now
private Vector3 screenPoint;
private Vector3 offset;
void Start()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void Update()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint)+offset;
transform.position = curPosition;
}