- Home /
RTS building snap to grid
Hi I am trying to figure out how to get my building to snap to a grid when I move it around. Right now it follows my mouse position just fine, but I can't get it to snap. Please help!
private Vector3 temp;
// Update is called once per frame
void Update () {
temp.x = Mathf.Round(Input.mousePosition.x);
temp.y = Mathf.Round(Input.mousePosition.y);
temp.z = Camera.main.transform.position.y - 0.5f;
transform.position = Camera.main.ScreenToWorldPoint(temp);
I just need the x and y to snap, the z position is just fine. Thanks! :)
Answer by jobo22 · Aug 02, 2017 at 06:49 PM
Finally got the snapping to work using this code
Vector3 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.y));
Vector3 finalPos = new Vector3(Mathf.Round(mousePos.x), Mathf.Round(mousePos.y), Mathf.Round(mousePos.z));
transform.position = finalPos;
This is all in void Update()
Answer by OrdinaryDev83 · Aug 01, 2017 at 07:41 PM
Try this :
Vector3 finalPos = Vector3.zero;
void Update(){
Vector3 cursorPos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
finalPos = new Vector3(Mathf.Round(cursorPos.x), Mathf.Round(cursorPos.y), [Z value here]);
}
It doesn't work. The cube wouldn't follow the mouse when I added transform.postion = finalPos, so I changed it to this
private Vector3 finalPos = Vector3.zero;
// Update is called once per frame
void Update () {
Vector3 cursorPos = Input.mousePosition;
finalPos = new Vector3($$anonymous$$athf.Round(cursorPos.x), $$anonymous$$athf.Round(cursorPos.y), Camera.main.transform.position.y - 0.5f);
transform.position = Camera.main.ScreenToWorldPoint(finalPos);
But it still wont snap to the grid. :(
It should work, it depends on your Camera settings.
I just have a default camera with no settings changed except its rotation and position. I will hopefully figure it out. Thank you for helping! :)
Your answer
Follow this Question
Related Questions
Best solution for Grid-based building system? 0 Answers
Snap to grid not working for me 1 Answer
How to drag gameobject (only x y) snapped to a grid? 2 Answers
Gizmo won't stop snapping to grid. 1 Answer