using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ZombieMovement : MonoBehaviour
{
    public float rightMax;
    public float leftMax;
    public float speed;
    [Range(0, .3f)] public float _movementSmoothing = .05f;

    private Rigidbody2D _rigidbody2D;
    private Transform _transform;
    private bool goingRight = false;
    private float horizontalMove = -1f;
    private Vector3 _velocity = Vector3.zero;


    private void Awake()
    {
        _rigidbody2D = GetComponent<Rigidbody2D>();
        _transform = GetComponent<Transform>();
    }

    // Update is called once per frame
    void Update()
    {
        AjustPlayerDirection();
    }

    private void AjustPlayerDirection() 
    {
        if (_transform.position.x < leftMax && !goingRight)
            Flip();
        else if (_transform.position.x > rightMax && goingRight)
            Flip();
    }

    private void Flip() 
    {
        horizontalMove *= -1f;
        goingRight = !goingRight;
        Vector3 theScale = _transform.localScale;
        theScale.x *= -1;
        _transform.localScale = theScale;
    }

    private void FixedUpdate()
    {
        Move();
    }

    private void Move() 
    {
        Vector3 targetVelocity = new Vector2(horizontalMove * speed, _rigidbody2D.velocity.y);
        _rigidbody2D.velocity = Vector3.SmoothDamp(_rigidbody2D.velocity, targetVelocity, ref _velocity, _movementSmoothing);
    }
}
