How to Knockback


(christopf) #1

Its me again :> This time i want to create a knockback on collision with an enemy entity. (After 5 collisions the player entity get removed) To accomplish this i tried it this way

	protected var knock:Boolean = false;



	override public function update():void
	{
		super.update();
		
		knockingBack();

		if (collideTypes(["schatten"], x, y))
		{
			trace("contact");
			knock = true;
		}
	}

	private function knockingBack():void
	{
		var k:uint = 4;
		
		if (knock = true)
		{
			if ((lastRichtung = "Nord") && (k != 0))
			{
				y += Geschwind +100 / 2;
				k--;
			}
			else if ((lastRichtung = "Sud") && (k != 0))
			{
				y -= Geschwind +100 / 2;
				k--;
			}
			else if ((lastRichtung = "West") && (k != 0))
			{
				x += Geschwind +100 / 2;
				k--;
			}
			else if ((lastRichtung = "Ost") && (k != 0))
			{
				x -= Geschwind +100 / 2;
				k--;
			}			
			else if (k == 0)
			{
				knock = false;
			}	
		}

	}

But this leads to my player falling out of the window. can you find the problem?


(rostok) #2

try changing if (knock = true) to if (knock). and all other if’s have singe = instead of ==


(christopf) #3

jep, just had that idea a few minutes ago while laying in bed. when i change it to == its working! thank you. (but when i dont put this behind or doing this with == instead of =

		if (knock = false)
		{
			
		}

the hero get shot out of the window to the direction he came from. i cant explain it to myself, maybe you have a hint? + the knockback is pretty abrupt. i tried it with

		if ((lastRichtung == "Nord") && (k != 0))
		{
			y += k * 0.3;
			k--;
		}

but its still very fast (k is 40)) …i get some sleep now, maybe i find a solution tomorrow… gn8


(Ssnyder Coder) #4

it looks like the ‘k’ variable in your knockingBack() method should be a private field instead of a local variable. Otherwise, it will always start at 4 when that method is called and never reach 0 to end the knockback effect. Perhaps just something like this (k changed to knockTime for readability):

protected var knock:Boolean = false;
private var knockTime:uint = 0;


override public function update():void
{
	super.update();

	knockingBack();

	if (collideTypes(["schatten"], x, y))
	{
		trace("contact");
		knock = true;
		knockTime = 4;
	}
}

private function knockingBack():void
{
	if (knock)
	{
		if ((lastRichtung = "Nord") && (knockTime != 0))
		{
			y += Geschwind +100 / 2;
			knockTime--;
		}
		else if ((lastRichtung = "Sud") && (knockTime != 0))
		{
			y -= Geschwind +100 / 2;
			knockTime--;
		}
		else if ((lastRichtung = "West") && (knockTime != 0))
		{
			x += Geschwind +100 / 2;
			knockTime--;
		}
		else if ((lastRichtung = "Ost") && (knockTime != 0))
		{
			x -= Geschwind +100 / 2;
			knockTime--;
		}			
		else if (knockTime == 0)
		{
			knock = false;
		}	
	}

}

The code could still be improved, but this should work now.


(christopf) #5

Thanks, this works even better!