Ignore Collider Grip, Object / Player Knockback
I made a 2D Jump and Run and i want if a Player hit a trap that he get knockback. If i jump (then i am not grounded) and i hit the trigger from my trap my Code :
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
if (Time.time > lastAttackTime + attackCooldwon)
{
lastAttackTime = Time.time;
other.GetComponent<PlayerHealth>().TakeDamage(damage);
if(gameObject.name == "LeftCollider")
{
other.GetComponent<PlayerControl>().controlEnabled = false;
transform.Translate(0, 0, 0);
other.GetComponent<Rigidbody2D>().velocity = new Vector2(-7, 5);
}
if (gameObject.name == "RightCollider")
{
other.GetComponent<PlayerControl>().controlEnabled = false;
transform.Translate(0, 0, 0);
other.GetComponent<Rigidbody2D>().velocity = new Vector2(7, 5);
}
}
}
}
it works perfect but if I walk in my trigger (then i am grounded) i will get no knockback to the X aixs and only low to the Y aixs. And If i change the Physic Matirals to (Friction = 0) no Grip it wouldn't work. I think it is because the Player collide to the ground and then he can't get knockback.
Thanks for your help.
Answer by Pengocat · Jan 29, 2017 at 04:59 PM
You may have better luck using AddForce() instead of setting the velocity directly.
void OnTriggerEnter2D(Collider2D other)
{
// ...
if (gameObject.name == "RightCollider")
{
other.GetComponent<PlayerControl>().controlEnabled = false;
other.GetComponent<Rigidbody2D>().AddForce(new Vector2(7, 5), ForceMode2D.Impulse);
}
// ...
}
this line transform.Translate(0, 0, 0);
seems redundant by the way.
Your answer
Follow this Question
Related Questions
Using a different physic material on a single object depending on the object colliding with it? 0 Answers
Physics without rigid body- bouncing effect to collider on hit 0 Answers
i need help making this code work with 2D physics. 0 Answers
2D Physics not working correctly 1 Answer
sometimes Polygon collider do not work properly and no collision happens 0 Answers