Contents:

Creating a Playable Grid

A staple within PvZ is the grid that the player can place plants onto. An excellent tutorial by DDreaming Game allowed me to gain insight on the basics of making a grid and having items lock to these cells.

The grid is made by a simple Instantiation based on the the set width and height of the grid which allows those cells to be populated and positioned correctly.

Creating a 9 (Width) by 6 (Height) Cell Grid for future items to be placed on.

Creating a 9 (Width) by 6 (Height) Cell Grid for future items to be placed on.

The next step is being able to interact: by utilising a RayCast sent from the camera to the grid, we can dictate the mouse’s position on the screen and see which cells we are hovering over.

The initial code for this was not working in Unity 2022.1.19f1 as intended, but by re-factoring the Raycasting code from the tutorial into my own, the grid snapping on hover worked as intended.

Initially, the  did not take the ScreenPosition properly.

Initially, the RayCast did not take the ScreenPosition properly.

Tutorial RayCast:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray, out var enter))
{
	  mousePos = ray.GetPoint(enter); ...
}

After a rework on the  element, the box now snaps correctly to the grid.

After a rework on the RayCast element, the box now snaps correctly to the grid.

Re-factored RayCast:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;

if (Physics.Raycast(ray, out hit))
{
	  mousePos = hit.point; ...
}

Once this is working as intended, we can then add a click element which lets us place elements onto the grid, as well as implementing an isPlaceable check to stop overlapping units.