0
\$\begingroup\$

I want to move and deploy 3D objects in the grid, like bakery 2(Storm8 Studios). How do you make a grid like that? For example, make a 5x5 grid and move it to a touchdrag. I'd like you to give me some advice.

Pictures for reference: https://lh3.googleusercontent.com/Kwp9i9ExRboeQCtM65sztw3tqEL9R76zZzB9U6j5vs98ueF9ksOU3huMdZqv4KPDZ2E=w2590-h1430

\$\endgroup\$
1

1 Answer 1

1
\$\begingroup\$

Probably the simplest solution in your case would be to set the location of the object using the mouse position as a reference and then adjust it using a mathematical round operation, something like this:

public class SnapToGridControl : MonoBehaviour {
    public Transform objectToMove;
    private Vector3 objectLocation;
    private Camera _cam;

    void Start () {
        _cam = Camera.main;
    }

    void Update () {
        if(!objectToMove)
        {
            Debug.LogAssertoin("No object was selected.");
            return;
        }

        //Creating a ray pointing forward based on the Cursor and camera positions
        Ray ray = _cam.ScreenPointToRay(Inupt.mousePosition);
        RaycastHit hit;

        //Checking if the ray is hitting something, maybe the ground
        if(Physics.Raycast(ray, out hit, 100f, Layer.GetMask("Ground")))
        {
            //Adjusting the position and rounding the coordinates to snap to virtual grid
            objectPosition = new Vector3(Mathf.RoundToInt(hit.point.x), Mathf.RoundToInt(hit.point.y), Mathf.RoundToInt(hit.point.z));
        }

        //Setting the object's position
        objectToMove.position = objectPosition;
    }
}

For more info about casting rays from the Camera check here: https://docs.unity3d.com/Manual/CameraRays.html

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .