My little death code

if (bodyCollider.IsTouchingLayers(LayerMask.GetMask(“enemies”)))

    {

        myAnimator.SetTrigger("Dying");

        isAlive = false;

        SpriteRenderer mySpriteRenderer = GetComponent<SpriteRenderer>();

        mySpriteRenderer.color = Color.red;

        myRigidbody.velocity = new Vector2 (-(Mathf.Sign(transform.localScale.x)*10f),3f);

    }

it worked great and as intended, when the enemy hits me (whether while walking or idling) it throws the player in the opposite direction and changes it’s color to red. the only problem is if the enemy hits the player from behind, it still throws him but only a small amount for some reason. is there a way to fix that?
thank you

1 Like

You need to calculate the direction to throw the player in.

What you need is to determine the direction to the attacking enemy. To do this, you would need to know who has hit the killing blow. You don’t show a lot of code, so I’m not sure how you will do that but for the sake of the post, let’s assume you have a reference to that enemy transform. What we want is to move away from the enemy, so we can get the direction vector from the enemy to the player, and then extend it:

Vector2 throwDirection = (transform.position - attacker.transform.position).normalized;

We normalize the vector because we are only interested in the direction. Now, you can apply a force (or update the velocity like you did) in the direction we just calculated:

Vector2 throwVelocity = throwDirection * 10f; // Stretch the direction to 10f
throwVelocity.y = 3f;
myRigidbody.velocity = throwVelocity;

I’m not sure how this would work setting the velocity. Usually, you’d apply force instead. Something like

myRigidbody.AddForce(throwDirection * 10f);
1 Like

Thank you that worked flawlessly! but can i ask you what does “normalized” or “normalize” do?

When you normalize a vector, you are essentially just setting the length (magnitude) to 1. When the vector is, say, (1, 0, 0) it’s length is already 1, but when it’s (1, 1, 0) it’s length is 1.41. So, normalizing is to scale it back to 1. In that case it will become (0.71, 0.71, 0). These are rounded so it’s not 100% accurate.

When we work with directions, it’s usually better to use the normalized vector - also called Unit Vector

You can read more about unit vectors here: Unit Vector - Wikipedia


Edit:
A quick example of use is in a character controller. When the player presses the forward key, the character moves forward at a specific speed. The same goes for pressing the right key. But when the player presses both forward and right, the character will move diagonally, but faster than the required speed. This is what I showed above. If the walking speed is 1, then the character will move diagonally at a speed of 1.41. Too fast. So, we can normalize the movement vector and that will bring the diagonal speed back to 1.

3 Likes

thank you

Privacy & Terms