Using Ease Functions for Warrior Movement

Moving with Physics

In Unity, there are various ways to make an object move but the basic idea is to change the objects position every frame. In my game, a warrior only needs to move forward as soon as it spawns. It will only stop after hitting an enemy warrior or the enemy base.

Before we proceed, it is important to note that I attached a rigidbody and a collider component to the warrior object. I decided to do that to simplify my scripts. Using Unity's physics framework, I only need to implement the actions required to a warrior during collisions; I don't have to compute for the collisions itself.

Since I am using the physics framework, updating the warrior position is done in `FixedUpdate` to help Unity with better physics calculations. Here's the basic or the linear implementation:

``````[SerializeField] private float _speed;

private void FixedUpdate()
{
Vector3 pos = transform.localPosition;
pos += transform.forward * _speed * Time.fixedDeltaTime;
transform.localPosition = pos;
}``````

The linear movement seems okay but I want to add a little more juice to the movement. After spawn, I want the warrior to start slow and eventually gain momentum. I want to keep the physics simple – instead of adding frictions and acceleration, I simulated them by using an ease function.

``````[SerializeField] private float _speed;
[SerializeField] private float _topSpeed;

private float _easeValue;

private void OnEnable()
{
_easeValue = _speed;
}

private void FixedUpdate()
{
float currentSpeed = _speed * EaseIn(_easeValue);
currentSpeed = Mathf.Min(currentSpeed, _topSpeed);

Vector3 pos = transform.localPosition;
pos += transform.forward * currentSpeed;
transform.localPosition = pos;

_easeValue += Time.fixedDeltaTime;
}

private float EaseIn(float easeValue)
{
// ease in sine
return 1f - Mathf.Cos(easeValue * Mathf.PI * 0.5f);
}``````

Summary

I demonstrated both linear and eased movement. Both implementations are valid and it is up to you to choose which of the movement computation is best for your project.