Skip to content

Instantly share code, notes, and snippets.

@ircnelson
Forked from unity3dcollege/Grid.cs
Created May 25, 2018 12:50
Show Gist options
  • Save ircnelson/941d7a07a9c4cc08fb8cfbb09c61cf89 to your computer and use it in GitHub Desktop.
Save ircnelson/941d7a07a9c4cc08fb8cfbb09c61cf89 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class Grid : MonoBehaviour
{
[SerializeField]
private float size = 1f;
public Vector3 GetNearestPointOnGrid(Vector3 position)
{
position -= transform.position;
int xCount = Mathf.RoundToInt(position.x / size);
int yCount = Mathf.RoundToInt(position.y / size);
int zCount = Mathf.RoundToInt(position.z / size);
Vector3 result = new Vector3(
(float)xCount * size,
(float)yCount * size,
(float)zCount * size);
result += transform.position;
return result;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.yellow;
for (float x = 0; x < 40; x += size)
{
for (float z = 0; z < 40; z += size)
{
var point = GetNearestPointOnGrid(new Vector3(x, 0f, z));
Gizmos.DrawSphere(point, 0.1f);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment