The next requirement is to add enemy aggression which here we will define as the enemy ramming the player if it’s close to it. Not all enemies will have this aggressive behavior so we will need to randomize it and use weights if it is to be enabled or not.
I’ve added this attributes on the enemy:
private bool _hasAgression = false;
private bool _hasAgressionEnabled = false;
[SerializeField]
private int _aggressionWeight = 20;
On initialization, it will assign if the enemy has aggressive behavior or not:
weightRequired = Random.Range(0, 101);
Debug.Log("Random Weight Required: " + weightRequired);
if (_aggressionWeight >= weightRequired)
{
_hasAgression = true;
}
else
{
_hasAgression = false;
}
On the player, I added a child GameObject with tag PlayerPresenceFront for the enemy to detect if it hits this collider:
Then, on OnTriggerEnter2D, if this collider is detected it will enable _hasAgressionEnabled if _hasAgression is true.
if (other.CompareTag("PlayerPresenceFront"))
{
if (_hasAgression)
{
_hasAgressionEnabled = true;
}
}
I also turned off aggression if collider no longer collides with the Enemy:
if (collision.CompareTag("PlayerPresenceFront"))
{
if (_hasAgression)
{
_hasAgressionEnabled = false;
}
}
Then, on Enemy movement, we will sway the x value if enemy aggression is enabled:
float xValue = 0f;
if (_player != null && _hasAgressionEnabled)
{
float distance1 = Vector3.Distance(new Vector3(transform.position.x + 1f, transform.position.y, transform.position.z), _player.transform.position);
float distance2 = Vector3.Distance(new Vector3(transform.position.x - 1f, transform.position.y, transform.position.z), _player.transform.position);
if (distance1 < distance2)
{
xValue = 1f;
}
else if (distance1 > distance2)
{
xValue = -1f;
}
else
{
xValue = 0f;
}
}
Vector3 movement = new Vector3(xValue, -1, 0);
Debug.Log(movement);
transform.Translate(movement * _speed * Time.deltaTime);
As you can see above, if enemy aggression is not detected then x value will default to 0.
Now, I have some enemies with aggressive behavior: