My questions:
Does using a logic layer cause an issue with performance when working with FixedUpdate?
Is it a bad idea to use a logic layer for game development?
My Scenario:
I have two objects. A “Player” object which is a MonoBehavior, and a “PlayerLogic” object which is a Singleton. I have a method called “Flip” that flips the sprite on user input.
If I move the Flip method to the Player object and call it in the FixedUpdate call, the sprite flips fine.
If I move the Flip method to the PlayerLogic object and call PlayerLogic.Flip in the FixedUpdate method, the sprite begins to stutter on user input.
The code:
The code below is causing a stutter/jitter:
public class Player : MonoBehaviour
{
public float speed = 2.5f;
private bool isFacingRight = true;
private Animator animator;
private Rigidbody2D rb2d;
private PlayerLogic playerLogic {
get { return LogicRepository.instance.playerLogic; }
}
// Use this for initialization
void Start()
{
animator = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
rb2d.freezeRotation = true;
}
// Update is called once per frame
void FixedUpdate()
{
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
AnimateSprite(x, y);
}
public void AnimateSprite(float x, float y)
{
float isMoving = Mathf.Abs(x) + Mathf.Abs(y);
animator.SetFloat("Speed", isMoving);
rb2d.velocity = new Vector2(x * speed, y * speed);
if (x > 0 && !isFacingRight)
{
playerLogic.Flip(isFacingRight, transform);
}
else if (x < 0 && isFacingRight)
{
playerLogic.Flip(isFacingRight, transform);
}
}
}
Here is the logic layer:
public class PlayerLogic : Singleton<PlayerLogic>
{
public void Flip(bool isFacingRight, Transform transform)
{
isFacingRight = !isFacingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}