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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Need help to restrict players from shooting 'backwards'

Discussion in '2D' started by Spikelino, May 11, 2018.

  1. Spikelino

    Spikelino

    Joined:
    May 11, 2018
    Posts:
    2
    I've created a script where the bullet shoots towards your mouse. My problem is that you can face right and still shoot left. I've tried a if statment that only executes if the angle is greater than x and less than x when you're facing left/right., so that you cant shoot otherwise.

    I don't really know how eulerAngles or Quanterion works really...


    A piece of the script:

    Vector3 sp = Camera.main.WorldToScreenPoint(brl.transform.position);
    Vector3 dir = (Input.mousePosition - sp).normalized;



    Quaternion rotation = Quaternion.Euler(0, 0, Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg);

    Debug.Log(rotation.z);

    if ((rotation.z > 0.75f && rotation.z < 1 && chara.transform.rotation.y == 1) || (rotation.z > -0.5f && rotation.z < 1 && chara.transform.rotation.y == 1) || (rotation.z < 0.75f && rotation.z > 0 && chara.transform.rotation.y == 0) || (rotation.z < 0f && rotation.z < -0.5f && chara.transform.rotation.y == 0))
    {
    if (chara.GetComponent<WeaponChange>().lastwpn == "UZI")
    {
    barrel.transform.parent.Find("Fire").GetComponent<SpriteRenderer>().enabled = true;
    }

    if (chara.GetComponent<WeaponChange>().lastwpn == "AK")
    {
    barrelAK.transform.parent.Find("Fire").GetComponent<SpriteRenderer>().enabled = true;
    }


    ammo = ammo - 1;
    brl.GetComponent<AudioSource>().Play();


    bullet1 = Instantiate(bullet, brl.transform.position, rotation);

    bullet1.tag = chara.GetComponent<WeaponChange>().lastwpn;
    bullet1.GetComponent<Rigidbody2D>().velocity = dir * 1000 * Time.deltaTime;

    Destroy(bullet1, 2f);
    StartCoroutine(waitforfire());
    }
     
  2. knobblez

    knobblez

    Joined:
    Nov 26, 2017
    Posts:
    223
    You wont get help if you don't put code in code form. check the text editor options
     
  3. knobblez

    knobblez

    Joined:
    Nov 26, 2017
    Posts:
    223
    sorry for double posting but i wanted to keep these posts separate.

    just realized this is 2d -.- doh.

    you need to just remember the last direction faced.
    Code (CSharp):
    1.  
    2. public int LastKey;//1 = up, 2 = down, 3 = left, 4 = right
    3.  
    4. if (Input.GetKeyDown(KeyCode.S))
    5. {
    6. LastKey = 2;
    7. }
     
    Last edited: May 11, 2018