Pick correct spot on grid
I am trying to create a grid so I can place blocks on the grid for a brick breaker style game. I need to raycast the mouse position into the grid and pick the correct spot on the grid to place the brick. I have looked up a couple of answers around the net, but none of them seem to be accurate enough to pick the correct grid spot. My code is below. The function GetNearestPointOnGrid is what I am using to find the point that should give me the spot on the grid I would need. That function is based on answers that I found around the net similar to this one https://answers.unity.com/questions/126406/how-to-instantiate-a-prefab-onto-a-grid.html
using UnityEngine;
public class Grid : MonoBehaviour {
public Transform CollisionPlane;
public Vector2 Size = new Vector2(5, 5);
public Vector2 Scale = new Vector2(2, 1);
public float PointRadius = 0.125f;
// Use this for initialization
void Awake ()
{
SetupCollisionPlane();
}
// Update is called once per frame
void Update ()
{
}
private void OnDrawGizmos()
{
// draw points
Gizmos.color = Color.green;
for (int x = 0; x < Size.x+1; x++)
{
for (int y = 0; y < Size.y+1; y++)
{
Gizmos.DrawSphere(new Vector3(x * Scale.x, y * Scale.y, 0), PointRadius);
}
}
// draw Vertical lines
Gizmos.color = Color.red;
for (int x = 0; x < Size.x+1; x++)
{
Gizmos.DrawLine(new Vector3(x * Scale.x, 0, 0),
new Vector3(x * Scale.x, Mathf.Pow(Scale.y, 2) * Size.y, 0));
}
// draw horizontal lines
for (int y = 0; y < Size.y+1; y++)
{
Gizmos.DrawLine(new Vector3(0, y * Scale.y, 0),
new Vector3(Scale.x * Size.x, y * Scale.y, 0));
}
}
private void SetupCollisionPlane()
{
// scale
CollisionPlane.localScale = new Vector3(Size.x * Scale.x,
Size.y * Scale.y,
0.01f);
// position
CollisionPlane.position = new Vector3(CollisionPlane.localScale.x * 0.5f,
CollisionPlane.localScale.y * 0.5f,
0.01f);
}
public Vector3 GetNearestPointOnGrid(Vector3 pos)
{
Vector3 position = pos - transform.position;
position = new Vector3(Mathf.Floor((position.x / Size.x) * Size.x,
Mathf.Floor((position.y / Size.y) * Size.y),
0);
return position;
}
}
Your answer
Follow this Question
Related Questions
Change order of adding elements in a List 1 Answer
Why does it matter if I use one GameObject's position or another's when drawing a mesh? 1 Answer
How to prevent the player to move beyond certain x-position value 3 Answers
Moving instantiated Objects to target locations 1 Answer
Need help with this code? thanks. 2 Answers