- Home /
Translating multiple GameObject using the mouse (2D)
Hello !
I've been searching through UnityAnswer, but didn't find the solution to my problem.
My project and camera are set to 2D. My scene is composed of nothing at the beginning, then using the mouse button i can create little GameObject made of a SpriteRenderer and a Collider.
Once a GameObject is created, clicking on it will select it (the gameobject will be added to a List). MouseDragging the gameobject will translate it to the mouse position. When right-clicking the GO get unselected. This is working perfectly. I also implemented a multiple selection function : I am able to create a square in order to select several GameObject. All of them are added to the list.
Then goes the tricky part : When several objects are selected, i would like, when mousedragging one of them, to move all the objects. Of course, If using the same function as for a single selected GO, all the objects will end having the same coordinates, while it's not what am looking for : i want them to keep there relative position. So for each gameobject am computing an offset from the mouse position, that i will add during the dragging to keep the distance. But it is not working : the translation is extremely slow, it's blinking, and when i release the mouse al the GO disappears. Sometime, while dragging, the selection just disappears and error messages are telling me that its position is not valid (infinity).
Here is my code :
public void MoveSelected(Vector3 mpos){ //mpos are the coordinates of the mouse
Vector3 offset;
foreach (GameObject Selected in CurrSelected) { //CurrSelected is a list where are stored all the Selected gameobjects starting a 2.
offset = Selected.transform.position - mpos; //computing the offset between the mouse position and the GO, for each.
Selected.transform.position += offset; //adding the offset to the new position of the object.
}
}
By the way, here is the code am using to determine mpos :
public Vector3 WorldfromScreen(){
return camera.ScreenToWorldPoint (Input.mousePosition); //Compute world coordinates from screen coordinates
}
What am i doing wrong ? Thank you very much !
Fabien.
Your answer
Follow this Question
Related Questions
Prefabs position gets changed 0 Answers
Using gameObject.translate moves it farther than expected 1 Answer
Firing arrow in direction depending on Camera 2 Answers
Plz Help me ! How to tanslate JS to C#? 2 Answers
force traslation 1 Answer