I am coding a game using LibGdx and I have an array with all of my wall objects that the player can collide with. For those who don't use LibGdx, I am talking about LibGdx's Array class which provides the same functionality as an ArrayList but it's built with memory efficiency in mind. When I check for collision, I am having to go through every wall in the array and check for collision like this:
for(Wall w : walls) {
if(w.bounds().contains(player.bounds()) {
// handle collision
}
}
I realized this was inefficient because I am going through every wall even if that wall is off the current view of the map. Obviously, if I am checking for collision with walls currently in the camera's viewport (this means they are currently visible by the player) then there is no point in going through the whole array because the player can't collide with them until they come into view. I was thinking of making my game a bit more efficient by only checking for collision with walls close to the player. In my game, I have all of the walls snapped onto a grid with cells 32x32 px. I really don't know how I could create more efficient searching for collision. Could I use like a map of some sort which uses a vector2 position for its key and then look up the player's position and look through walls within a certain range from the player's position in the map? I am just really lost on how to have code that won't go through all 100+ walls in my game when there are only 10 current possible walls that the player could touch because of where it currently is. Does this make any sense? Could someone explain a good way to do something like this? Thanks so much.
There are lots of collision alghoritms out there, you will need to find one that suits your need.
One solution I can think of on the top of my head is:
Keep your wall list sorted on their coordinates. If you create a new wall, use insertion sort to resort your array. When you want to check for collisions, take the objects coordinates (in this case probably the player that is running) and do a binary search to find the closest wall to the player. Then calculate if the player and this wall collides. If the closest wall isn't causing a collision, you can be pretty confident that no other wall is as well.
Each wall is on one or more of these 32x32px grids. Let the coordinates of a grid be x and y. If a grid contains a wall, enter this into a
HashMap<CoordPair,Set<Wall>> xy2wall
To investigate where a location is in contact with a nearby wall, use the coordinates of the location to determine a small set of grid coordinates, fetch the set or sets of Walls mapped by these CoordPairs. I guess the Player.bounds() can provide a suitable set of coordinates.
If the 32x32 grid results in too many entries, you can always use a coarser grid.
I once came into the same realization that you have while developing a top down rpg.
There are more walls than you can imagine in a top down rpg.
Here is how I solved it:
First: Segment the map into zones ie.) draw your map on paper or something and cut it up into parts.
Second: Record the pixel boundaries for each segmented section of the map.
Third: Check where your players location is with respect to the boundaries.
Finally: Only check the walls within those boundaries.
In a realm of infinite walls this is not any more efficient (speaking about Big O) but for all practical purposes this is effective in cutting down on lookup times
if (boundary1.contains(player1)) {
for(Wall w : Boundary1Walls) {
if(w.bounds().contains(player.bounds()) {
// handle collision
}
}
}
else if (boundary2.contains(player1)) {
for (Wall w : Boundary2Walls) {
if(w.bounds().contains(player.bounds()) {
// handle collision
}
}
}
....
Continue in this fashion
Take note... I did it like this before going to college for software development, so I did not make use of data structures such as BST which could be used to store walls with respect to their coordinates. Making your lookup time extremely fast.
In a game that I am creating at the moment I want to make it so that the player holds a gun.
Right now I have the gun and the player as one image and it works but it would be alot better to have the gun and the player as seperate images because right now it looks like the player shots bullet from it's forehead and if I would have the gun as an seperate object it would be easier to make the bullets shot out of the gun. I will also implement a weapon switching system later on so then it will also be easier to have the guns as seperate objects.
The problem is that because I have used an AffineTransform and Vector2d to rotate the player to always face the mouse cursor I can't manage to make it so that it always looks like the player holds the gun. It's more that sometimes the gun is a little inside the player, sometimes it looks fine and sometimes the gun is floating in the air, either infront of the player or at the side of the player.
Is there any easy way that I could make the gun "stick" to a part of the player object?
You probably "just" need to use the right anchor, for example in rotate. To make this easier, imagine that the Gun bitmap (or Shape?) has the same size as the player.
I tried to illustrate that in this drawing:
The left image is the player, and the right image is the gun. Notice that the gun image has the same dimension as the player image, but is of course almost empty. The red point would be the anchor of the rotation - for example in the center of the image, even though that doesn't matter. If you superimpose the gun on the player and rotate both using the same anchor the gun will always be in the right place.
If you know your linear algebra you can of course also solve this analytically. But I would suggest first getting it to work the way you want, and then exploring more elegant solutions from there. A good quick read I found is this four part blog post. Part 3 and 4 touches on your question. If you want a more thorough introduction any linear algebra textbook will do, or you might like this free online course.
In our game we make the sword and shield stick to the appropiate position of the sprite of the player/enemy by having helpermethods like the ones below:
public int getPlayerLeftHand()
public int getPlayerRightHand()
And everytime the player is drawn (in our game he always has a shield and sword) his sword/shield is drawn at his right/left hand respectively by calling the above methods. The implementors (player/enemy) decide where their hands are so you don't have to worry at all about whether they are rotated or not, you know that every time you call the method the implementors take care of giving you the correct coordinates, in our case by checking what direction they are facing then displacing the coordinates appropriately.
Alternatively if you want a more OOP approach you could pass the player/enemy to the weapon and let them decide how and where they want to be rendered.
You solve this by accumulating transformation matrices.
First, you have a transformation matrix that positions the player. Next, you define a matrix that positions the gun in the hand of the untransformed player. Multiply the two matrices together, and you have one that positions the gun in the hand of the transformed player.
Finally, while you're at it, write a transform matrix that positions a bullet relative to the barrel of the gun. Multiply all three matrices together, and your bullet is where it belongs.
Your 3d graphics library will have routines to do all this for you.
I have to be blunt though: if you don't already know all this, you may have bitten off more than you can chew.
I really need help. I am making a game app for my final year project. It is a simple game where you have to shoot a ball into a target by rebounding of walls or angled blocks. However i need help in 2 areas:
the shooting mechanism is similar to that of stupid zombies. There is a crosshairs where you touch on the screen to indicate which direction you want the ball to be shot at. On release the ball should move into that direction and hopefully gets into the target and if not gravity and friction causes it to come to a stop.
The problem is how do I code something like this?
I need the ball to rebound of the walls and I will have some blocks angled so that the ball has to hit a certain part to get to the target. The ball will eventually come to a stop if the target is not reached.
How can I make a method to create the collisions of the wall and blocks?
I have spent the last weeks trying to find tutorials to help me make the game but have not found much specific to the type of game I am making. It would be great if sample code or template could be provided as this is my first android app and it is for my final year project and i do not have much time left.
Thank you in advance
akkki
Your question is too generic for stack overflow no one is going to do your project for you. Assuming you have basic programming experience if not get books and learn that first.
Assuming you already chose Android because of your tag, and assuming 2d game as it is easier.
Pre requests:
Install java+eclipse+android sdk if you havent already.
Create a new project and use the lunar landar example, make sure it runs on your phone or emulator.
Starting sample:
The lunar landar has a game loop a seperate thread which constantly redraws the whole screen, it does this by constantly calling the doDraw function. You are then supposed to use the canvas to draw lines, circles, boxes, colours and bitmaps to resemble your game. (canvas.draw....) Lunar landar does not use openGL so its slower but much easier to use.
Stripping the sample:
You probably don't want keyevents or the lunar spaceship!
Delete everything in the onDraw function
Delete the onKeyUp, onKeyDown
Delete any errors what happen
Create a new
#Override
public boolean onTouchEvent(MotionEvent event){
return false;
}
Run it you should get a blank screen, this is your canvas to start making your game... You mentioned balls, break it down to what a ball is: A position and direction, create variables for the balls x,y direction_x and direction_y the touch event will want to change the balls direction, the draw event will want to move the ball (adding the direction x,y to the ball x,y) and draw the ball (canvas.drawCircle(x,y,radius,new Paint())) want more balls search and read about arrays. Most importantly start simple and experiment.
2 collisions
Collisions can be done in the dodraw function and broken down to: moving an object, checking if that object has passed where it is supposed to go and if so move it back before anyone notices.... There are many differently techniques of collision detection:
If your walls are all horizontal and vertical (easiest) then box collisions checks the balls new x,y+-radius against a walls x,y,width and height its one big if statement and google has billions of examples.
If your walls are angled then your need line collision detection, you basically have a line (vector) of where your ball is heading a vector of your wall create a function to check where two lines collide and check if that point is both on the wall and within the radius of your ball (google line intersection functions)
or you can use colour picking, you draw the scene knowing all your walls are red for example, then check if the dot where the new ball x,y is, is red and know you hit
Good luck, hope this helped a little, keep it simple and trial and error hopefully this gets you started and your next questions can be more specific.
I'm building a pacman game. Basically, I want to have a map representation of this window consisting of blocks/tiles. Then as the pacman character/ghost moves i would change their position on the map to represent what's on the screen, and use that for collision detection etc.
How can I build this map, especially since the screen is made of x,y coordinates, so how can I correctly represent them in tiles/on this map?
I know it's tempting to start thinking of objects and interfaces but have you thought about a 2-dimensional array with each element representing 40 pixels or something? I don't remember pacman being pixel accurate when it came to collision, more a question of the direction each piece was moving in.
Generally you have an abstract representation that doesn't reference pixels as such (for example, maybe the Pac-Man maze is simply w units wide), and then you have a linear transformation (you know, y = mx + b) to carry the abstract representation to actual pixels.
To make it concrete, let's say that you want your abstract representation to be 100 units wide, and you want to render it as 400 pixels. Then the transformation is just scrn_x = 4 * x.
Kind of difficult to come up with this without writing it myself but.
First you'll need to create entity definitions that implement ICollidable. Entities would include ghosts, pacman, dots and powerups.
Each element in the map would contain, along with other information, a list of all present entities with a sort of "position" value for added precision. The ICollidable interface would include not only logic for determining which entities collide with one another (ghosts don't collide with dots for example.) but determining if they're in position to collide with one another. IE if pacman is entering a space from the right and a ghost is leaving that space from the left there's no collision. It will also help determine when exactly pacman has eaten a dot so that graphically it looks correct. IE if you destroy a dot right as pacman enters a space it's going to disappear before he even touches it graphically.
Your sprites such as pacman and the ghost are represented by positions (x,y). To determine if they collide with each other, use this psuedocode:
sprites = [ ... list of sprites ... ]
for i1=0 to len(sprites):
sprite1 = sprites[i1]
for i2 = i1+1 to len(sprites):
sprite2 = sprites[i2]
if (sprite1.x-sprite2.x)^2+(sprite1.y-sprite2.y)^2 < radius_of_sprites^2:
collide(sprite1, sprite2)
Note that this doesn't involve the map at all. We can check for collisions between pacman and the map separately. The key trick here is you divide the pixel coordinate of each of pacman's sides (top, bottom, left, right) and check for collisions. For example, if pacman is going to the right, we need to check the right edge for a collision:
pacman_tile_x = (pacman.x+tilesize/2)/tilesize # added tilesize/2 to check the middle of pacman
pacman_tile_y = pacman.y/tilesize + 1 # +1 because right edge is 1 tile to the right of the sprite's coordinate
if tile[pacman_tile_x][pacman_tile_y].is_a_wall:
... wall collide code ...
Now, if you have a huge number of sprites on the screen, you can optimize the sprite-to-sprite collision detection by storing which sprites exist on any particular tile in the map, and so you only have to check against sprites in adjacent tiles. But for a first pass and for this pacman game, it's probably not a necessary optimization.
So I'm building the pacman game in Java to teach myself game programming.
I have the basic game window with the pacman sprite and the ghost sprites drawn, the pacman moves with the arrow keys, doesn't move beyond the walls of the window, etc. Now I'm trying to build the maze, as in this picture:
Without giving me the direct/complete solution to this, can someone guide me as to how this can be built? I'm talking only about the boundaries and the pipes('T' marks) here which you can't go through and you have to go around. Not the dots which the pacman eats yet.
Here are my questions:
1) What's the most efficient algorithm/method for creating this maze? Will it have to be drawn each time the paint() method is called or is there a way to draw it only at the start of the game and never again?
2) How will this actually be drawn to the screen? I assume the fillRect() will be used?
3) Any hints on collision detection (so the pacman/ghosts can't go through the walls) would be helpful.
4) Any hints on how the vacant space between the pipes will be calculated so the dots can be filled between them will also be very helpful.
Thanks
I wouldn't do it that way.
I'd draw the graphical map and then create a 2D data array which represents the map. The data map would be responsible for determining collisions, eating dots, where candy is and where the ghosts are. Once all the logic for everything is handled just use the 2D array to display everything in their proper pixel coordinates over the graphical map.
For example the user is pressing the left key. First you determine that pacman is at element 3, 3. Element 3, 2 contains information denoting a wall so you can implement the code to make him ignore the command.
EDIT:
Each element would represent about where a dot could be. For example:
No, looking at the board I would say the array would look something like this.
d,d,d,d,d,d,d,d,d,d,d,d,w,w,d,d,d,d,d,d,d,d,d,d,d,d
d,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,d
p,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,p
d,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,d
d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d
And so on. You might want to pick a more flexible data structure than just characters however since some areas need to contain a bunch of different information. IE even though the ghost spawning area is blank, pacman isn't allowed in there. The movement of the ghosts and pacman is different for the side escapes, the candy spawn point is a blank spot but if you want to remain flexible you'll want to denote where this is on a per map basis.
Another thing you'll want to remember is that pacman and the ghosts are often inbetween points so containing information that represents a percentage of a space they're taking up between 1,2 and 1,3 is important for collision detection as well as determining when you want to remove dots, powerups and candy from the board.
You can paint the map into a BufferedImage and just drawImage that on every paint(). You'll get quite reasonable performance this way.
If you are happy with the walls being solid, you can draw each square wall block with fillRect. If you wish to get the same look as in the picture, you need to figure how to draw the lines in the right way and use arcs for corners.
The Pacman game map is made of squares and Pacman and the ghosts always move from one square to the neighbouring square in an animated step (i.e. you press right, the pacman moves one square to the right). That means that collision detection is easy: simply don't allow moves to squares that are not empty.
I do not understand what you are trying to ask here.
1) Just to give my advice on redrawing. Something that you can do if you find redrawing the entire image is slow, is determine only the elements that have changed on the screen and redraw those. An approach for this would be the following: Determine the sprites that have moved. Determine (approximate) a rectangle around those sprites. Redraw those rectangles only. This way you are only refreshing parts of the screen and not the whole screen. This should result in an increase in performance over redrawing the entire screen.
The other answers have been reasonable for the other questions you have asked.