- Home /
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!
As a suggestion: please define your grid dimensions as a const somewhere
public const float CELL_WIDTH = 0.64f;
Also, keep in $$anonymous$$d that float comparison is difficult to get right. Due to rounding errors you will need to compare within some epsilon
Answer by robertbu · Aug 01, 2014 at 02:25 AM
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.
Thank you, this should work wonders. Regarding your note on the grid scale, the reason i've done this way is because my blocks are 64x64 pixels. $$anonymous$$any people recommended against setting the pixel to unit scale to 1, since the blocks would eventually come really far away from the 3d origin, which apparently causes problems. A block would be 64x64 units, and that's not really practical, is it? Do you think having a really tall level of 64x64 blocks is okay, or will it cause problems?