Knockback based on enemy position
Hello guys, I was able to code a knockback based on the player movement, but I wanted one based on the enemy position.
Here is my current collision code on the object named "Cactus":
private void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "Player" && theplayer.cantakedamage == true)
{
switch(gameObject.tag)
{
//if its a trigger 'Dano1', play script hurtplayer(damage1)
case "Dano1":
FindObjectOfType<HealthController>().HurtPlayer(damage1);
break;
}
}
}
This code plays the script to damage calculation and plays the 'knockback' void on the player:
public void HurtPlayer(int damage1)
{
currenthealth -= damage1;
//plays the script 'knockback' on the player
thePlayer.Knockback(new Vector3(0,0,0));
}
This code now applies knockback code on the player based on its actual speed:
public void Knockback(Vector3 direcaoknock)
{
//direcao is the variable for movement on my character
direcao += new Vector3(-direcao.x * knockbackforce, direcao.y + (knockbackforce * 10), -direcao.z * knockbackforce);
}
I want to apply the knockback relative to the object named "Cactus".
Thanks!
Answer by parad0x · Jan 29 at 11:03 PM
You can use the normal of the other
you got from OnTriggerStay i think.
ContactPoint2D contact = other.GetContact(0);
// Multiplying with -1 coz we need to apply force on the opposite direction of the normal
Vector2 forceToBeApplied = new Vector2(knockBackXForce * contact.normal.x * -1, knockBackYForce * contact.normal.y * -1);
targetBody.AddForce(forceToBeApplied, ForceMode2D.Impulse);
Not sure if the API for the GetContact
is the same, but you get the idea
Your answer

Follow this Question
Related Questions
2D Knockback problem 2 Answers
2D Melee with knockback based on the "OverlapCircleAll" function 1 Answer
Help with 2D topdown knockback 0 Answers
Script not working as it should 1 Answer
how to make knockback and slowmotion when hit by enemy 0 Answers