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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Help with angles and quaternion please!

Discussion in 'Scripting' started by iso250, Oct 25, 2015.

  1. iso250

    iso250

    Joined:
    Apr 19, 2015
    Posts:
    28
    Hello all.

    I'm making a 2D top down shooter. I have enemies that shoot at the player and I'm fine with coding this. For the record I'm using this to code the instantiation of the enemy weapons fire.

    Vector3 FirePos = Camera.main.WorldToScreenPoint(transform.position);
    Vector3 FireDir = Input.mousePosition - FirePos;
    float angle = Mathf.Atan2(FireDir.y, FireDir.x) * Mathf.Rad2Deg;

    Laser_X_Instance = Instantiate(Laser_X, transform.position, Quaternion.AngleAxis(angle, Vector3.forward)) asRigidbody2D;

    What I'm having trouble with is making them inaccurate.

    How do you code the instantiate so that rather than have perfect aim, the enemies will shoot to a random angle that is within +-0.5 degrees of perfect aim? I have looked through the tutorials and forums but cannot find how to do this and I have to admit that I struggle with quaternion.

    Can anybody please help me with this?
     
    Last edited: Oct 25, 2015
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    Just add Random.Range(-0.5f, 0.5f) to angle.
     
    iso250 likes this.
  3. iso250

    iso250

    Joined:
    Apr 19, 2015
    Posts:
    28
    angle += Random.Range(-0.5f, 0.5f)?

    Is it really that easy??
     
  4. iso250

    iso250

    Joined:
    Apr 19, 2015
    Posts:
    28
    Just tried it. Thank you so very much! Everything I was trying was so very much more complicated than that!