Math in Unity : Grid and Bitwise operation (Part VIII)

Now that we have a little clearer idea of how to keep track of our Tiles, let’s dive deeper.
In many games of this type, we have a grid, and we have tokens or objects placed on top of the grid.
We will therefore see how to check the Tile through bitwise operations.

First of all, let’s check the GetTileState method to get a better idea of what’s going on.

Just like SetTileState (), instead of a long, the method returns a bool if the Type bit is 1 or false if it is 0.

To test it, I simply create a sphere with this scale (and make it a prefab)

So what I want to try is this: every time I click on the grid with the left mouse button, I want to instantiate a sphere.
But not on all Tile, only on those we decide.

In order to do this, we will need the Update method and a Raycast.

Let’s start creating a ray, so we’ll use the ScreenPointToRay camera method

Here’s the documentation
https://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html

This returns a ray going from camera through a screen point.
Inside we need a Vectro3 position, and we pass the Mouse Position.

We finish the piece of code by instantiating the sphere at the point where we click.

To make everything more clean, we can set the parent to the object we hit.
Thanks to the variable “hit” we have the reference to everything we hit with the Raycast

And we set localPosition on a new Vector3 (0f, 1f, 0f);
So our sphere is instantiated on top of our grid and not “inside”.

As always, in order to perform operations we need a long to set the Tile.
I called it sphere

And inside the Raycast we setting the sphere

Now, SetTileState needs coordinates as well as a long as parameters.
To pass the rows and columns to it, we simply cast explicitly in int the float of hit.collider.gameobject.transform.position.x and hit.collider.gameobject.transform.position.z

It gives us an error because hit.collider.gameobject.transform.position.x ia s a float

Change the code to this

After the explicit cast, everything works fine

It works, but not quite as we would like.
In fact the sphere is instantiated, in each Tile, but also above the other spheres.

In the next article we will give some rules so that we can instantiate the sphere ONLY in some cells.

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!