Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Created October 9, 2017 00:28
Show Gist options
  • Save unity3dcollege/95305935e256df5a3fe157e526b15b22 to your computer and use it in GitHub Desktop.
Save unity3dcollege/95305935e256df5a3fe157e526b15b22 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