Skip to content

Instantly share code, notes, and snippets.

@IanPedroV
Created May 18, 2019 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanPedroV/b7952998da7e06fb86ea0831af1bc863 to your computer and use it in GitHub Desktop.
Save IanPedroV/b7952998da7e06fb86ea0831af1bc863 to your computer and use it in GitHub Desktop.
public class GridHighlight : MonoBehaviour
{
public Transform tilePrefab;
public Transform newTile;
public Vector3 objectPos;
Vector3 mousePos;
private Grid grid;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void Awake()
{
grid = FindObjectOfType<Grid>();
}
void OnMouseOver()
{
if (!(Input.mousePosition.x == mousePos.x && Input.mousePosition.y == mousePos.y))
{
if (newTile != null)
{
Destroy(newTile.gameObject);
}
mousePos = Input.mousePosition;
mousePos.z = 70f;
Vector3 objectPos = Camera.current.ScreenToWorldPoint(mousePos);
objectPos.y = 1.05f;
// newTile = Instantiate(tilePrefab, objectPos, Quaternion.Euler(0,0,0)) as Transform;
RaycastHit hitInfo;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hitInfo))
{
PlaceTileNear(hitInfo.point);
}
}
}
private void PlaceTileNear(Vector3 clickPoint)
{
var finalPosition = grid.GetNearestPointOnGrid(clickPoint);
newTile = Instantiate(tilePrefab, finalPosition, Quaternion.Euler(0, 0, 0)) as Transform;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment