2D Slashing Game. Need help with the slashing mechanic.

Hi guys, still very new at this, making a hack and slash 2d game. So right now I have the slashing to work like this:

	RaycastHit2D hit = Physics2D.Raycast (position, transform.position);

		if (hit.collider.gameObject.tag == "Ogre") 
		{
			Debug.Log ("You made a hit!");
			dmg.Hit ();
		}

And this is in the enemy class:

public void Hit()
{
	enemy_cur -= dmg;
}

So when the mouse goes over the enemy collider, the current health of the enemy drops by 0.05f. This works fine, but the issue that I can’t currently wrap my head around is that because it detects collision and is constantly updating if i just leave the mouse over the monster, its health will drop without stopping. How do I prevent that? How can I limit one slash to one collide, thus lowering the enemy’s health once, until another slash comes in. I’ve tried experimenting with a timer cooldown, but it makes the game less smooth to play as there’s now a waiting period before the next attack.

Any help would be appreciated. Thanks guys.

EDIT: Would having an if check for entering and exiting the collision be a sufficient solution? I’m now trying to implement this but I seem to be having trouble adding it into the hit.collider if.

Provide more details about your class (Collision functions, ...)

1 Answer

1

Why don’t you try to use OnCollisionEnter? It will happen only for once when collision starts

    void OnCollisionEnter(Collision collision){
    if(collision.gameObject.tag=="Ogre")
     //do whatever will happen when hit
    }

No, oncollisionenter will work alone. Try to remove raycast and return me if it works or not.

Without a raycast it won't detect the mouse movements that I'm using to detect slashes. I've just tried this: void OnCollisionEnter2D(Collision2D coll) { if (coll.collider.gameObject.tag == "Ogre") { dmg.Hit (); Debug.Log ("You entered the monster"); } } Nothing happens when I slash across the screen.

I've tried a boolean method before, and it also doesn't work. I've just tried with your codes and nope, still nothing. Thank you so much for your help so far, I really appreciate it. I'm guessing because it's being updated at every frame it keeps detecting the collision at every update. Not really sure though.