15/01/2019

Script C# do personagem (com anti-colisões)

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

public class Player : MonoBehaviour
{
    public float maxSpeed = 10f;
    public float forcaPulo = 100;
    bool grounded = false;
    bool walld = false;
    public Transform groundCheck;
    public Transform wallCheck;
    float groundRadius = 0.2f;
    float wallRadius = 0.2f;
    public LayerMask whatIsGround;
    public LayerMask whatIsWall;
    bool doubleJump = false;
    bool noAr = false;

    Animator anim;

    void Start()
    {
        anim = GetComponent<Animator>();

    }

    void Update()
    {

        Rigidbody2D rigidbody = GetComponent<Rigidbody2D>();
        float vSpeed = rigidbody.velocity.y;
        float movimento = Input.GetAxis("Horizontal");

        if (vSpeed != 0 && movimento != 0 && !grounded)
        {
            noAr = true;
        }

        if (grounded && vSpeed == 0.0)
        {
            GetComponent<Animator>().SetBool("jumping", false);
            noAr = false;
        }

        if (!grounded)
        {
            GetComponent<Animator>().SetBool("walking", false);
            anim.SetBool("Ground", false);


            if (!grounded && Input.GetKeyDown(KeyCode.Space) && walld)
            {

                GetComponent<Animator>().SetBool("jumping", false);
                anim.SetBool("Ground", false);

            }
        }
        if (grounded && Input.GetKeyDown(KeyCode.Space))
        {
                   
            anim.SetBool("Ground", false);
           
            GetComponent<Animator>().SetBool("jumping", true);

            if (!noAr)
            {
                GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 150));
            }


        }

     

    }


    void FixedUpdate()
    {
        Rigidbody2D rigidbody = GetComponent<Rigidbody2D>();
       

        grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
        anim.SetBool("Ground", grounded);
        walld = Physics2D.OverlapCircle(wallCheck.position, wallRadius, whatIsWall);
        anim.SetBool("Wall", walld);
        anim.SetBool("No Ar", noAr);



        anim.SetFloat("vSpeed", rigidbody.velocity.y);

        float move = Input.GetAxis("Horizontal");
        anim.SetFloat("Speed", Mathf.Abs(move));
        rigidbody.velocity = new Vector2(move * maxSpeed, rigidbody.velocity.y);

        if (grounded)
        {
            doubleJump = false;
        }

       
     

        if (move < 0)
        {
            GetComponent<SpriteRenderer>().flipX = true;
        }
        else if (move > 0)
        {
            GetComponent<SpriteRenderer>().flipX = false;

        }

        }


}