This script allows you to create the effect of 2D characters appearing reflected in mirrors - while respecting their facing direction. It works by controlling a second character that is updated each frame according to the original character's state.
To use it:
- Set up your character to use Sprites Unity Complex animation.
- Duplicate the character you wish to mirror
- Remove the Player or NPC component for duplicated character (used for the mirror) but keep their Animator and sprite
- Create a new C# file called MirrorCharacter (below) and attach to the duplicated character.
- Assign the fields in the Mirror Character component's Inspector
- Use Unity's Sprite Mask component to limit rendering of the mirror character to the boundary of the mirror.
MirrorCharacter.cs:
using UnityEngine;
using AC;
public class MirrorCharacter : MonoBehaviour
{
public bool isPlayer;
public AC.Char originalCharacter;
public Animator _animator;
public Vector3 positionOffset;
private void Update ()
{
if (isPlayer)
{
originalCharacter = KickStarter.player;
}
if (originalCharacter == null)
{
return;
}
// Position
transform.position = originalCharacter.transform.position + positionOffset;
// Move speed
if (!string.IsNullOrEmpty (originalCharacter.moveSpeedParameter))
{
float moveSpeed = originalCharacter.GetAnimator ().GetFloat (originalCharacter.moveSpeedParameter);
_animator.SetFloat (originalCharacter.moveSpeedParameter, moveSpeed);
}
// Direction
if (!string.IsNullOrEmpty (originalCharacter.directionParameter))
{
int direction = originalCharacter.GetAnimator ().GetInteger (originalCharacter.directionParameter);
int flippedDirection = FlipDirection (direction);
_animator.SetInteger (originalCharacter.directionParameter, flippedDirection);
}
// Talking
if (!string.IsNullOrEmpty (originalCharacter.talkParameter))
{
bool isTalking = originalCharacter.isTalking;
_animator.SetBool (originalCharacter.talkParameter, isTalking);
}
}
private int FlipDirection (int direction)
{
// 0 = Down, 1 = Left, 2 = Right, 3 = Up, 4 = DownLeft, 5 = DownRight, 6 = UpLeft, 7 = UpRight
switch (direction)
{
case 0:
return 3;
case 1:
return 2;
case 2:
return 1;
case 3:
return 0;
case 4:
return 7;
case 5:
return 6;
case 6:
return 5;
case 7:
return 4;
default:
return direction;
}
}
}