Search Unity

Question Gun recoil power and angle

Discussion in '2D' started by Sudoki_, Jul 2, 2020.

  1. Sudoki_

    Sudoki_

    Joined:
    Mar 16, 2018
    Posts:
    4
    I'm using the location of the mouse on screen to output an constant force in the opposite direction..I'm fairly new to c# so wasn't sure if there is a better way to do it. As of now the y direction is always negative even when the mouse is below the player and the power on the x axis is not always the same...

    Code Below

    /------------------------------------------------------------------------------------------------------------------------------------------\

    private void recoil()
    {
    mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    direction = (mousePos - transform.position).normalized;
    if(direction.x > direction.y)
    {
    if(direction.x < 0)
    {
    direction.x = direction.x / -direction.x;
    direction.y = direction.y / -direction.x;

    }
    else
    {
    direction.x = direction.x / direction.x;
    direction.y = direction.y / direction.x;
    }
    }

    if (direction.y > direction.x)
    {
    if (direction.y < 0)
    {
    direction.y = direction.y / -direction.y;
    direction.x = direction.x / -direction.y;

    }
    else
    {
    direction.y = direction.y / direction.y;
    direction.x = direction.x / direction.y;
    }
    }

    rb.velocity = new Vector2(-direction.x * recoilPower, -direction.y * recoilPower);
    }