How do I attach a rectangle to a line?

So, I’m trying to create Pac Man and I’m not sure on how to do so. My best idea so far was to attach the rectangle (which will be Pac Man himself, the player) to certain invisible lines, as if he is a train on a railroad. The player could only move within those lines that function as railroads.
How could I execute such thing?
Perhaps I shoud take another approach?
Thanks in advance!

1 Like

To draw pacman itself look at pie please it allows for an open mouth.

Now, there are different ways of doing this.

But since you need to draw also the walls of the labyrinth and the ghosts I would go for a grid. Each cell can either be path, wall, ghost or pacman.

Now you can use 2d array, see tutorials.

When moving pac man increase its position in the grid. (Either say x++ or y++ but this is the index of the grid not the screen position).

When there’s a wall in front in the next cell of the grid, pac man stops

1 Like

Yes, definetly take another approach. Although you could just measure the distance to the line to get wether he leaves the path, that is not really elegant…

A better way would be to check wether you can move there or not. For that, actually using single lines as paths might be problematic.

So just draw the walls, and check wether pacman can go „that“ way or not. If so, change direction/ continue moving, Else stop pacmans motion.

Also, you can store the intended direction and continuisly check that, like how in pacman you press down and when the turn comes, only then does he change direction.

If you intend to go for a pacman clone, go with @Chrisir ‘s suggestion. If you want the paths to be any shape, you‘d probably want to go with collission detection.


Why this definitely looks like a better solution! Thank you!

Thank you for your answer! I think I’ll try @Chrisir’s suggestion first, and if it go well I’ll try yours.


When you have a 2D array grid

You could have it of type int[][]

each cell could be a class Cell

It contains x,y and type (wall, path, pacman, ghost…)

you could define the x,y in a nested for loop x,y

Sometimes it is useful to start with a single rail – one line, with a pacman on it that can move back and forth only on that line.

Then add dots. Then turn it into a full maze of multiple lines, with ghosts.

Just so that you know, a full pacman is more complicated than a full Breakout or a full Frogger – the maze and controls can be challenging. For past discussions of Pacman projects, see also: