Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Gun recoil mechanic

Discussion in '2D' started by Sudoki_, Jul 8, 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);
    }
     
  2. Mooxe

    Mooxe

    Joined:
    Sep 18, 2013
    Posts:
    19
    Is this a topdown game or a platformer?