Мой персонаж всегда почему-то обоснован - PullRequest
0 голосов
/ 08 февраля 2019

Я хочу, чтобы мой персонаж выполнял анимацию прыжков только тогда, когда он заземлен.По какой-то причине isGounded возвращает false.Что мне сделать, чтобы он вернул true?

Я использовал Debug.Log, чтобы узнать, что мой код возвращает IsGounded как false, но я не знаю, что делать, чтобы сделать его верным, когда мой игрокКруговые коллайдеры касаются земли.

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

public class NewPlayerController : MonoBehaviour 
{
    private Rigidbody2D myRigidBody;
    private Animator anim;
    private SpriteRenderer sr;

    private bool facingRight;

    [SerializeField]
    private Transform[] groundPoints;

    [SerializeField]
    private float groundRadius;

    [SerializeField]
    private LayerMask whatIsGround;

    [SerializeField]
    private float movementSpeed;

    private bool isGrounded;

    private bool jump;

    [SerializeField]
    private float jumpForce;

    [SerializeField]
    private GameObject bullet;

    // Start is called before the first frame update
    void Start()
    {
        myRigidBody = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        sr = GetComponent<SpriteRenderer>();


    }
     void Update()
    {
        HandleInput();
    }
    // Update is called once per frame
    void FixedUpdate()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");

        isGrounded = IsGrounded();
        Debug.Log(isGrounded);
        HandleMovement(horizontal);

        Flip(horizontal);

        HandleLayers();

        ResetValues();
    }

    private void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jump = true;

        }
        if (Input.GetKeyDown(KeyCode.V))
        {
            ShootBullet(0);
        }

    }

    private void HandleMovement(float horizontal)
    {
        if (myRigidBody.velocity.y < 0)
        {
            anim.SetBool("Land", true);

        }

        myRigidBody.velocity = new Vector2(horizontal * movementSpeed, myRigidBody.velocity.y);
        anim.SetFloat("speed", Mathf.Abs(horizontal));

        if(isGrounded && jump)
        {

            isGrounded = false;

            myRigidBody.AddForce(new Vector2(0, jumpForce));

            anim.SetTrigger("Jump"); 

        }

    }
    private void Flip(float horizontal)
    {
        if(horizontal > 0 && !facingRight || horizontal <0 && facingRight)
        {
            facingRight = !facingRight;
            Vector3 theScale = transform.localScale;
            theScale.x *= -1;
            transform.localScale = theScale;
        }
    }
    private bool IsGrounded()
    {
        if (myRigidBody.velocity.y <= 0)
        {
            foreach (Transform point in groundPoints)
            {
                Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
                for (int i = 0; i < colliders.Length; i++)
                {
                    if (colliders[i].gameObject != gameObject)
                    {
                        anim.ResetTrigger("Jump");
                        anim.SetBool("Land", false);
                        return true;


                    }
                }
            }
        }
        return false;

    } 

    private void ResetValues()
    {
        jump = false;
    }
    public void ShootBullet(int value)
    {
        if (facingRight)
        {
            GameObject tmp = (GameObject)Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0,0,-90)));
            tmp.GetComponent<BulletBehaviour>().Initialize(Vector2.right);
        }
        else
        {
            GameObject tmp = (GameObject)Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0, 0, 90)));
            tmp.GetComponent<BulletBehaviour>().Initialize(Vector2.left);
        }
    }
    private void HandleLayers()
    {
        if (!isGrounded)
        {
            anim.SetLayerWeight(1, 1);
        }
        else
        {
            anim.SetLayerWeight(1, 0);

        }
    }
}

Я хочу, чтобы мой код возвращался как заземленный, как истина, когда мой игрок касается земли.По какой-то причине код возвращает false.

1 Ответ

0 голосов
/ 08 февраля 2019

Действительно глупая ошибка.Мне просто пришлось немного подправить землю и коробочные коллайдеры.Мне также пришлось сменить слой земли на правый, чтобы «whatIsGround» позволил моим коллайдерам круга обнаружить землю

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...