Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I am making a game in where it's topdown and you can place blocks how can I have a snap to grid game so its like you place a block and it snaps to a grid so you cant place squares on top of eachother. Im not asking you to write my code (I don't mind if u do) I just want to know how to do this. my code so far that would be helpful to luck at and get an idea of what I mean:

public static ArrayList<hellstone> hpf = new ArrayList<hellstone>();

for (int i = 0; i < hpf.toArray().length; i++) {
    hpf.get(i).render(g);
}

public void mouseReleased(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON1) {
            Comp.ml = false;
            if (Comp.play && Comp.money >= 100) {

                if(inventory.sel == 0){
                Comp.hpf.add(new hellstone(Comp.mx / 2 - 10, Comp.my / 2 - 10));
                Comp.money -= 100;
                }else if(inventory.sel == 1){
                    Comp.b.add(new board(Comp.mx / 2 - 10, Comp.my / 2 - 10));
                    Comp.money -= 100;
                }

            }
        } else if (e.getButton() == MouseEvent.BUTTON3) {
            Comp.mr = false;
            if (Comp.play) {

            }

        }

    }
share|improve this question

1 Answer 1

I figured it out. For each X and Y coordinate, I can do this:

x = (mousex / gridcellwidth) * gridcellwidth;
y = (mousey / gridcellheigt) * gridcellheigth;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.