- Home /
how do i instantiate game objects in an rts game
greetings i am a beginner in unity so please bear with me. i am trying to create an rts game. but i am facing a problem with implementing the rts style of creating buildings.the player would select the builder and click on the icon of the building he wishes to build. then the game object should be instantiated at the mouse's position and become locked to the cursor's movement. until he clicks again to place the building at a certain position. i don't want some one to do the code for me. i love programming so i want to do it myself. but i need help breaking it down to steps to where i can implement it.
Answer by trololo · Mar 22, 2014 at 02:09 PM
You can use this:
Camera.main.ScreenToWorldPoint(Vector3(mousePos.x, mousePos.y, Camera.main.nearClipPlane));
to translate your screen coordinates into world ones. The building you want to create follow that position, then when you click you stop moving it and it will stay at the desired location :)
Can you please explain "Camera.main.ScreenToWorldPoint(Vector3(mousePos.x, mousePos.y, Camera.main.nearClipPlane))" especially the "main.nearClipPlane" part
Actually, as you can't get the depth with Input.mousePosition (the z-axis is set to 0), you have to trace a raycast has zwoxy said. To prevent your raycast to hit the object that you want to place in the scene (and not the ground where you want to locate it), you should use a layer$$anonymous$$ask too. So define a new Layer in unity editor, and assign it to your ground (the "plane" where you want to place your buildings). Then you can use it that way: 1 << Layer$$anonymous$$ask.NameToLayer("Ground") in your raycast (http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html). Then you can use hit.point to place your building and you probably should ajust his depth by half of the building scale (hit.point.z - building.transform.localScale.z / 2). Good luck :)
Answer by zwoxy · Mar 22, 2014 at 01:53 PM
to get the mouse position in 3d space, you need to make a raycast that shoots from the camera to wherever the mouse is and then you can get the vector3 position from raycastHit.point
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to control order of executiing scripts? 1 Answer
rts developement 0 Answers
RTS rectangle selection system 3 Answers