Getting a sprite to snap to a tilemap when the mouse is moved

I will do my best to describe what I am trying to do, I’m not sure the title does a good job.

So I have 2 sprites that are 16x16px. One is a grass tile and the other is a mouse cursor. The grass tiles are laid out in a 20x20 grid starting at 0,0 and going to 19,19. I instantiate the cursor tile at 0,0 and what I’m looking to do is when I move the mouse I want the cursor tile to move with it but it has to snap to the grass tiles.

Does this make sense? I can get the cursor tile to move with the mouse, that’s not the problem. Getting it to snap to the grass tile is the problem.

Right now I have a hack fix in that works but it feels cheap. In my Tile.cs file I use OnMouseEnter and OnMouseExit to manipulate the mouse cursor. I’m looks for a more elegant method of moving the mouse cursor. Besides, while it has the effect of what I want I don’t think I’ll be able to use it like I want.

Note: This needs to work in game and not in the editor.

I think your solution sounds good, but I’m curious why you think it won’t work for what you want?

Off the top of my head I can’t think of the reason why using the OnMouseEnter/OnMouseExit would be bad. I sort of remember reading an article or watching a video about why raycasting is a better choice.

Infact I have switched to using a simple raycasting method and it does indeed work! I thought about my problem all day and realized I was trying to force something into Unity that I did in Flash. This was my first mistake. Once I removed the barrier of needing to do it the way I did it in Flash it because clear to me. All I needed to do was cast a ray from mouse and if it collided with a tile, just get the x and y of the tile and set the position of the cursor to that position.

I did it and it worked! So the moral of the story is use what is presented to you and don’t try to force old habits if they won’t work.

Cool :slight_smile: And I think enter/exit must work along those lines anyways. But glad ya got it working :slight_smile: