- Home /
addforce to rigidbody when hit
Hi,
I want to add force to the player rigidbody backwards.
So if a creature hits me i get thrown backwards a couple of meters.
I got this:
if (hit.rigidbody)
{
if (GetComponent<CharacterDamage>().Throw == true)
{
hit.rigidbody.AddForce(-hit.transform.forward * 2000);
hit.rigidbody.AddForce(hit.transform.up * 200);
}
Now when i get hit it does correctly what it supposed to if the player is facing the creature.
But when the creature sneaks up on the player from the back, the player gets thrown in the wrong direction.
How can i change it so that the player gets thrown in the right direction no matter where the creature hits me?
Answer by IgorAherne · Jan 22, 2017 at 11:50 PM
//compute vector (length one) from game object's pivot to the player's pivot:
Vector3 hitVector = (hit.transform.position - transform.position).normalized;
//if you want only horizontal plane movement, disable y-component of hitVector:
hitVector = (hit.transform.position - transform.position);
hitVector.y = 0;
hitVector = hitVector.normalized
hit.rigidbody.AddForce(hitVector* 2000 );
Yes thank you, that fixed the problem :) didn't knew about normalized.
I am also trying to figure this out, but am slightly confused. How do I set this up? Here is my code for dealing damage:
public class DamagePlayer : MonoBehaviour { public int damageAmount = 3;
//optional code
//do not plan to use
public bool destroyOnDamage;
public GameObject destroyEffect;
private void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag == "Player")
{
DealDamage();
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
DealDamage();
}
}
void DealDamage()
{
PlayerHealthController.instance.DamagePlayer(damageAmount);
//adding force when player is hit
//need to finish working on this
if (destroyOnDamage)
{
if(destroyEffect != null)
{
Instantiate(destroyEffect, transform.position, transform.rotation);
}
Destroy(gameObject);
}
}
}
Your answer