New enemy movement

Jaime
2 min readJun 12, 2021

--

The next requirement is to add a new enemy movement such as side-to-side, circling or coming into play from a different angle. For now, I’ll do side-to-side, but in the future I will add more articles on different movements.

Here are my new attributes to support side-to-side movement:

// Side to Side
[SerializeField]
private Vector3 _sideOrigin;
[SerializeField]
private float _sideBoundary = 1.0f;
[SerializeField]
private bool _sideMoveLeft = true;
private float _sideOffset = 0f;
enum Movement { Down, Circular, SideToSide };

When the Enemy instantiated, I recorded the spawn position to keep track of the middle x.

void Start()
{
//redacted
_sideOrigin = transform.position;
}

On the CalculateMovement() function, I checked the distance between the initial x value of the Enemy with the current value, if it has exceeded _sideBoundary. If not, it will continue to move based on its current direction. If not, it will flip to the other side. The offset is used to prevent jitter but at the same time it speeds up flipping direction. In hindsight, I could have used Coroutines instead to use a timer to flip from on direction to another.

Vector3 movement = new Vector3(xValue, -1, 0);
if (_movement == Movement.SideToSide)
{
float distance = Vector3.Distance(transform.position, new Vector3(_sideOrigin.x, transform.position.y, transform.position.z));
Debug.Log(distance);
if ( distance > _sideBoundary)
{
_sideMoveLeft = !_sideMoveLeft;
_sideOffset = 2f;
}
if (_sideMoveLeft)
{
movement.x = -1 - _sideOffset;
_sideOffset = 0;
}
else
{
movement.x = 1 + _sideOffset;
_sideOffset = 0;
}
}
transform.Translate(movement * _speed * Time.deltaTime);

Then, once the enemy reaches the bottom and re-spawns, we need to get change _sideOrigin again to get the middle x position.

if (transform.position.y <= -6)
{
transform.position = new Vector3(Random.Range(-11.3f, 11.3f), 7.2f, 0);
_sideOrigin = transform.position;
}

Now, the enemy is going to side-to-side as it’s moving down.

--

--

Jaime
Jaime

No responses yet