Та же кнопка выполняет другое действие в зависимости от того, к чему прикасается игрок - PullRequest
0 голосов
/ 25 декабря 2018

Я работаю над 2D бесконечной раннер-игрой для мобильных устройств.В игре используются 4 кнопки разных цветов, и в основном вы должны соответствовать цветам испытаний.

Пример

В настоящее время у меня есть базовая система атаки, которая работаетоснован на этом

И у меня возникают трудности с реализацией этого

Моя проблема:

  • Когдаперсонаж находится на вершине платформы, которая позволяет ему ускоряться, тогда какой бы цвет кнопки не соответствовал этому цвету, он не должен атаковать, но вместо этого используется функция ускорения.
  • Отпускание кнопки ускорения заставит персонажа прыгнуть, но я хочу, чтобы персонаж продолжал иметь скорость X ускорения, пока он снова не коснется земли.Учитывая, что игрок не нажал ни одной кнопки.

Я знаю, что на эталонных изображениях наблюдается постепенное увеличение скоростей, но давайте проигнорируем это и сосредоточимся на том, чтобы идея изменения скорости изменялась при необходимости.

Вот код моего персонажа:

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

public class PlayerController : MonoBehaviour
{

    [Header("Movement")]
    [SerializeField] float moveSpeed = 6;
    [Header("Jumping")]
    [SerializeField] float jumpHeight = 4;
    [SerializeField] float timeToMaxJumpHeight = .4f;
    [Header("Dashing")]
    [SerializeField] float dashSpeed = 10;
    [SerializeField] float dashDuration = 1;
    [Header("Ground Detection")]
    [SerializeField] Transform groundCheck;
    [SerializeField] float checkRadius;
    [SerializeField] LayerMask whatIsGround;
    [Header("Energy Blade")]
    //[SerializeField] EnergyBlade energyBlade;
    [SerializeField] GameObject myEnergyBlade;
    [SerializeField] float bladeHitboxDuration;

    private float targetFPS = 60;

    private float moveInput;

    // Jumping and gravity calculations
    private Vector2 gravity;
    private float jumpVelocity;
    private Vector3 velocity;

    // Checking flags
    private bool isGrounded;
    private bool isDashing;
    private bool canDash;
    private bool isJumping;

    // coroutines
    private IEnumerator myCoroutine; // General coroutine for the handler
    private IEnumerator dashingCoroutine;
    private IEnumerator attackCoroutine;

    //
    Rigidbody2D myRigidBody;

    // EnergyBlade properties
    BoxCollider2D energyBladeCollider;
    EnergyBlade energyBlade;

    // Speeding properties
    WorldColors platformColor = WorldColors.Neutral;
    bool speedingCommand;

    // Use this for initialization
    void Start()
    {
        myRigidBody = GetComponent<Rigidbody2D>();


        Physics2D.gravity = new Vector2(0, -(2 * jumpHeight) / Mathf.Pow(timeToMaxJumpHeight, 2)); // gravity calculation
        jumpVelocity = Mathf.Abs(Physics2D.gravity.y) * timeToMaxJumpHeight; // Jump velocity calculation

        // Energy Blade Assignments
        energyBladeCollider = myEnergyBlade.GetComponent<BoxCollider2D>();
        energyBlade = myEnergyBlade.GetComponent<EnergyBlade>();
    }

    private void FixedUpdate()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround); // change this to raycast

        Move();
        Jump();
    }

    void Update()
    {
        movementInput();
        ActionInput();
        ifNoSpeedingCommandOnGround();

    }

    // function to control the input of the player
    private void movementInput()
    {
        // move controls
        moveInput = Input.GetAxisRaw("Horizontal");
        // jump controls
        if (Input.GetKeyDown(KeyCode.Space))
        {
            isJumping = true;
        }
    }

    // function to control the player's horizontal movement
    private void Move()
    {
        float speed;
        speed = (isDashing) ? dashSpeed : moveSpeed;
        myRigidBody.velocity = new Vector2(moveInput * (speed * targetFPS) * Time.deltaTime, myRigidBody.velocity.y);

    }

    // function to allow the player to jump only if he's touching the ground
    private void Jump()
    {
        if (!isGrounded) return;
        if (isJumping)
        {
            myRigidBody.velocity = Vector2.up * (jumpVelocity * targetFPS) * Time.deltaTime;
            isJumping = false;
        }
    }



    private void ActionInput()
    {

        //print(IsSpeedingPlatform());

        // flag for hooks
        // flag for speeding platforms

        SpeedingInput(KeyCode.F, WorldColors.Green);
        SpeedingInput(KeyCode.G, WorldColors.Purple);
        SpeedingInput(KeyCode.H, WorldColors.Orange);
        SpeedingInput(KeyCode.J, WorldColors.Blue);


        EnergyBladeInput(KeyCode.F, WorldColors.Green);
        EnergyBladeInput(KeyCode.G, WorldColors.Purple);
        EnergyBladeInput(KeyCode.H, WorldColors.Orange);
        EnergyBladeInput(KeyCode.J, WorldColors.Blue);

    }


    private void ifNoSpeedingCommandOnGround()
    {
        print(speedingCommand);
        print(isGrounded);


        if (speedingCommand == false && isGrounded && !isJumping) // TODO CHECK TRHIS TO MAKE SURE IT DOESN'T CHECK IT IF THE PLAYER IS IN JUMPING PHASE
        {
            isDashing = false;
            print("speeding command is salfe and is grounded");
        }
        else if (speedingCommand == true)
        {
            isDashing = true;
        }

    }

    // function that sets the dashing to true if the color of the input and the platform match
    private void SpeedingInput(KeyCode key, WorldColors color)
    {
        //print("Speeding input enabled");
        //if (speedingCommand) return;
        if (Input.GetKeyDown(key))
        {
            speedingCommand = true;
        }
        else if (Input.GetKeyUp(key))
        {
            //speedingCommand = false;
            if (!isGrounded) return;
            isJumping = true;
        }

    }

    private bool IsSpeedingPlatform()
    {
        Collider2D[] collidedPlatforms = Physics2D.OverlapCircleAll(groundCheck.position, checkRadius, whatIsGround);
        if (collidedPlatforms.Length <= 0) return false;

        platformColor = collidedPlatforms[0].GetComponent<SpeedingPlatform>().platformColor;

        if (platformColor != WorldColors.Neutral)
        {
            return true;
        }
        else
        {
            isDashing = false;
            return false;
        }
    }

    private WorldColors SpeedingPlatformColor()
    {
        Collider2D[] collidedPlatforms = Physics2D.OverlapCircleAll(groundCheck.position, checkRadius, whatIsGround);
        if (collidedPlatforms.Length <= 0) return platformColor; // return the last color it was on if jumping/gliding

        return platformColor = collidedPlatforms[0].GetComponent<SpeedingPlatform>().platformColor;
    }


    /*
     * Energy Blade
     */

    // function that sends the color of the energy blade depending on the pressed key
    private void EnergyBladeInput(KeyCode key, WorldColors color)
    {
        if (Input.GetKeyDown(key))
        {
            BladeCoroutineHandler(color);
        }
    }

    // this function exists to prevent repeating the lines of stopping and starting coroutines.
    // Maybe it'll be converted to become a general function if needed
    private void BladeCoroutineHandler(WorldColors bladeColor)
    {
        if (myCoroutine != null) StopCoroutine(myCoroutine); // stop coroutine if it's already running
        myCoroutine = (bladeActiveHitbox(bladeColor)); // assign the coroutine
        StartCoroutine(myCoroutine); // start the assigned coroutine
    }

    // function to keep the collider of the energy blade to be enabled for x amount of time.
    private IEnumerator bladeActiveHitbox(WorldColors bladeColor)
    {
        energyBladeCollider.enabled = false; // disable the collider if it was already running from a previous attack
        energyBlade.bladeColor = bladeColor;// set blade color

        float duration = bladeHitboxDuration;
        while (duration >= 0)
        {
            energyBladeCollider.enabled = true;
            duration -= Time.deltaTime;
            yield return null;
        }
        energyBladeCollider.enabled = false;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...