I had an issue with units not turning when swinging the sword

In my scene I happen to have two units standing back to back. When I attack the enemy (or end turn and get attacked by it) with the sword slash, it failed to turn around and instead slashed forward (still hitting the enemy position correctly).

I added some debug log to tell me the values for the aimDir as well as the unit’s transform.forward and it reveald the aimDir.x being zero.

This is the output when first stepping one cell to the side:

To fix this I added a detection for it and a little “nudge” to start the rotation:

case State.SwingingSwordBeforeHit:
  float rotateSpeed = 10f;
  Vector3 aimDir = (targetUnit.GetWorldPosition() - unit.GetWorldPosition()).normalized;
  //Debug.Log($"Sword aiming Lerp ${aimDir}, forward {transform.forward}");
  if (Mathf.Abs(aimDir.x) < Mathf.Epsilon)
  {
    // if the target is exactly in the back, we get a rotation
    // of zero, so give it a little nudge to start turning
     aimDir.x += 0.01f;
  }
  transform.forward = Vector3.Lerp(transform.forward, aimDir, Time.deltaTime * rotateSpeed);
  break;

Privacy & Terms