I think you are going about it a little wrong, this is what I would do
- Create a rectangle around my player sprite like stated above and all other enemies.
- if the player intersects an enemy, you it will allow you to attack
- have the sprite just do an animate of swinging his sword at the enemy when you hit your attack button
- every time you hit your attack button do some calculations to see if your melee attack hits or misses.
- if the melee attack hits, draw the animation for a hit and vice versa for a miss
So basically, you only need to worry about 2 rectangles and not a rectangle around your weapon or anything.
I believe something along the lines of this would be the easiest approach and would work better, and would
make your game run smoother. It’s also a lot less confusing.
So basically, in your player and enemy classes you would want a method like this
public Rectangle getBounds()
{
return new Rectangle(x,y,width,height); //x and y are location on screen, width and height are the sprites dimensions
}
Then, in your game loop you would just check for collision with an enemy. could be something like this for example.
if you have multiple enemies and they are stored in an array or array list
for(int i = 0; i < enemies.size(); i++)
{
if(player.getBounds.intersects(enemies.get(i).getBounds())) //if player rectangle intersects enemy rectangle
{
//Do stuff
}
}
Here is an example of a collision detection stub from one of my games
//This code is in a game loop that is constantly being looped therefor, playerRect is constantly getting updated
Rectangle playerRect = player.getBounds();
for(int i = 0; i < getPathSize(); i++)
{
Path currPath = (Path) getPath(i);
Rectangle currRect = currPath.getBounds();
if(playerRect.intersects(currRect))
{
if(player.getY() < currRect.y)
{
player.grounded = true;
player.setGroundHeight(getPath(i).getBounds().y + 1);
player.correctY(getPath(i).getBounds().y);
break;
}
else if(player.getY() > currRect.y)
{
if(player.isRising())
{
mam.playTrack("bonk");
player.setPeak(true);
}
}
if(player.getX() < currRect.x)
{
player.shoveLeft(.5);
player.setDx(0);
}
else if(player.getX() > currRect.x)
{
player.shoveRight(.5);
player.setDx(0);
}
}