Posted: Mon Nov 19, 2012 12:14 am Post subject:
Question to programmers(algorithm help)
I need some help with a few lines of code. People familiar with Java, C or C++(and probably more) can help out here.
So, I am making a game, a copy of the infamous game called World Hardest Game.
Every time a MovableObject(in most cases, this is an enemy) moves a step, a function is called to see if this enemy have touched the main character(which means the game is over/you died).
Example:
In this case, the function would have returned true, which means the main character is colliding with the enemy.
The red one is the character you play as, and the green one is an enemy, or the opposite(does not matter).
I have written a piece of code that works, but the code is slow as hell and cause immense lag if you have more than ten objects.
My code:
Code:
/**
* Checks if the movable object is touching the main character.
* @return True if the object and the main character are interacting, otherwise, false.
*/
public boolean isColliding(MovableObject object)
{
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
for (int oy = 0; oy < object.height; oy++)
for (int ox = 0; ox < object.width; ox++)
if(posY + y == object.posY + oy && posX + x == object.posX + oy)
return true;
return false;
}
Variables height and width is the height and width of the character/enemy. posY and posX is the current position of the object(the upper-left corner).
Can someone please give me a code that is super fast? QUICK_EDIT
You do many unnecessary comparisons by going through every single tile of the game board. Instead compare only the positions of each object against the maincharacter position.
This way you reduce the amount of comparisons from more than 100 down to 10.
hold every single object in a list/array
//go through each object
for (int i=0; i<objects.length; i++)
{
if (object.x==maincharacter.x)&&(object.y==maincharacter.y) return true;
}
Maybe also search in other forums which specialize in game coding. There are surely more efficient ways like using matrices. _________________ SHP Artist of Twisted Insurrection: Nod buildings
You can post new topics in this forum You can reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum