This site requires JavaScript, please enable it in your browser!
Greenfoot back
Monserus
Monserus wrote ...

2018/11/24

A question about snapping an object to another object

Monserus Monserus

2018/11/24

#
Hi, I'm currently trying to recreate the "battleship" game in Greenfoot. Right now you're able to drag a ship to the field (the tiles where you play on). The problem is, that you're also able to put a ship between multiple tiles (e.g. putting a 2-tile ship in the middle of 4 tiles, which makes it 4 tiles large). A solution to this would be to make ships automatically snap to the tiles where their (mostly) located at. I wanted to know if thats even possible and if so, a short explanation would be really nice. Here's the code of the ship (the drag-function):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class BB extends Schiffe
{
    /**
     * Act
     */
    public void act()
    {
        dragShip();
    }  
    public void dragShip()
    {
        if(Greenfoot.mouseDragged(this))
        {
           MouseInfo mouse = Greenfoot.getMouseInfo();
           setLocation(mouse.getX(),mouse.getY());         
        }
    }
}
The field consists of 10x10 tiles, 100 tiles in total. Each tile is an object (using a loop to create multiple tiles of the same object). I think the information given is enough to understand everything (otherwise I'll happily add the missing information) and hopefully being able to help me. Many thanks in advance!
danpost danpost

2018/11/24

#
Monserus wrote...
Right now you're able to drag a ship to the field (the tiles where you play on). The problem is, that you're also able to put a ship between multiple tiles (e.g. putting a 2-tile ship in the middle of 4 tiles, which makes it 4 tiles large). A solution to this would be to make ships automatically snap to the tiles where their (mostly) located at. I wanted to know if thats even possible and if so, a short explanation would be really nice.
I will try to explain as best I can. First, let's define a ship of length 2 or 4 to be an even ship and one of length 3 or 5 to be an odd ship. Odd ships can be placed in a straight-forward manner. They can be placed oriented horizontally or vertically at any tile with some edge restrictions. Even ships, also with edge restrictions, can be placed horizontally or vertically between tiles. The set of possible locations depends on the orientation of the ship. Fortunately, the arrangement of possible locations with either orientation is a standard grid shape. Hopefully, that is sufficient enough information to get you on your way (use the orientation of the even ships to your advantage).
You need to login to post a reply.