How would I code an object to snap to a grid?

questions
answered

#1

Hey! I have something I’m working on but I need help. Id like to separate the screen into a grid of tiny, even, invisible squares. Like invisible grid paper. Then whenever the screen it tapped, a sprite will set its position to the middle of the nearest invisible square. This needs to be done without using clones and I’d prefer if it could be simply limited to a “setpos” block inside a “when the screen is tapped or pressed” block. Any ideas would be awesome!


#2

I’m not an advanced coder like you, but I would make a whole bunch of squares, make a command for “when square clicked set position to x square y square”. I don’t know if that helps (or even if it will work) but here you go! :grin:


#3

But if I wanted to cover the entire screen I would need clones but because of something else in the project I can’t use clones. Thanks for trying though!


#4

Here’s some code that should help:


(tap images for better quality)
(You can change the “Grid Square Size” variable to anything you want, it just (as the name suggests) sets the width of the squares in the grid.)

Here’s a visual representation of the grid, with the circle representing the object:

(Hopefully that made sense, if not then just let me know and I’ll try to explain it more clearly.)


#5

That’s exactly what I needed! Thank you! :grin:


#6

It’s pretty simple.



Just copy and paste this into y, and replace last touch x with last touch y.
What this does is make sure it’s the nearest multiple of fifty, so the default hopscotch editor grid.



Hope this helps.


#7

Oh so simple


#8

Ok! Thanks everyone! I don’t really have anything else to do with this topic now so should I recycle it or just abandon it?


#9

You should just keep it here in case people add to it or others want to look at it and use it


#10

Keep it as it is so that if someone else has this problem they can search for it and find this topic.


#11

It seems like your question already has been answered, and I don’t have anything to add, really.


#12


Thanks again for the help with my project. I’ll probably add more to the project later but here’s the first version! I wanted to make a pixel pad that wasn’t limited to clones and lets the player choose size, and type of pixel.