Skip to content
Snippets Groups Projects
PlayerMovement.cs 1.86 KiB
Newer Older
/*
 *      Script par Valentin Bloch      
 *
 */

public class PlayerMovement : MonoBehaviour
{
    public float speed;
    private Rigidbody2D myRigidbody;
    private Vector3 change;
    public PlayerState currentState;

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
        myRigidbody = GetComponent<Rigidbody2D>();

        animator.SetFloat("moveX", 0);
        animator.SetFloat("moveY", -1);

    }

    // Update is called once per frame
    void Update()
    {
v.bloch's avatar
v.bloch committed

        change = Vector3.zero;
        change.x = Input.GetAxisRaw("Horizontal");
        change.y = Input.GetAxisRaw("Vertical");

        if(currentState == PlayerState.walk)
        {
            UpdateAnimationAndMove();
        }

v.bloch's avatar
v.bloch committed
        Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
        pos.x = Mathf.Clamp01(pos.x);
        pos.y = Mathf.Clamp01(pos.y);
        transform.position = Camera.main.ViewportToWorldPoint(pos);
    }
    void MoveCharacter()
    {
        myRigidbody.MovePosition(transform.position + change * speed * Time.deltaTime);
    }

    void UpdateAnimationAndMove()
    {
        if (change != Vector3.zero)
        {
            MoveCharacter();
            animator.SetFloat("moveX", change.x);
            animator.SetFloat("moveY", change.y);

            animator.SetBool("moving", true);
        }
        else
        {
            animator.SetBool("moving", false);
        }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("factory"))
        {
            Debug.Log("perte de vie");
            this.GetComponent<PlayerNature>().LooseNature(20);
        }