Check if object is on grid

Hello, my game is made up of a 0.64x0.64 unit grid of blocks. The player can move sideways, but the movement is limited to these grid locations (if you press right, the character moves right until it hits the next grid spot). This is my current implementation:

var horizontalInput: float;
var targetPosition: Vector3;
private var moveSpeed: float = 1f;
function Start () {
	horizontalInput = Input.GetAxis("Horizontal");
	targetPosition = transform.position;
}

function Update () {
	if (transform.position.x == 0f || transform.position.x == 0.64f  || transform.position.x == 1.28f || transform.position.x == 1.92f || transform.position.x == 2.56f || transform.position.x == 3.2f || transform.position.x == 3.84f) {
		if (Input.GetButton("Horizontal")) {
			targetPosition.x = transform.position.x+(0.64f*Input.GetAxis("Horizontal"));
		}
	}
	

	transform.position = Vector3.MoveTowards(transform.position,targetPosition,moveSpeed*Time.deltaTime);
}

However, As you can see, the if statement that evaluates wheter the character is on a grid position is awful. How do I go about finding out if the character is on a grid spot in a nice manner?

Thanks!

The easiest solution based on the code you have here is to replace your if() on line 10 with:

 if (transform.position == targetPosition) {

Note that the comparison between Vector3s has some ‘slop’ so that direct comparisons works. It does not suffer from the same problem as directly comparing floating point numbers as outlined by @VesuvianPrime.

If you wanted to only compare the ‘x’ value as you’ve done in your code, you could do:

 if (Mathf.Abs(targetPosition.x - transofrm.position.x) < someSmallValue) {

A note about your code not related to your question: when creating grids like this, if at all possible use Integer values rather than values like 0.64f. You can always move the camera and/or change the OrthographicSize and/or change the FieldOfView to get a fit for an integer layout. And so many things are easier to code with integers.