How to Instantiate an object on a plane that is orthogonal to the player?

I’m trying to Instantiate gameobjects randomly on a plane orthogonal to the direction the player is looking. The script I wrote only works when the player is looking down the z axis and the rotation is (0,0,0). Any other rotation of the player causes the gameobjects to not Instantiate correctly as the plane isn’t moving because I’m just adding to the x and y components. How do I get them to instantiate correctly for any rotation?

using UnityEngine;
using System.Collections;

public class planespawn : MonoBehaviour {

  public GameObject projectile;

  void Update () {
      if(Input.GetButton("Fire1") ){    

          // for random placement 

          float xRand = Random.Range (-2f, 2f);
          float yRand = Random.Range (-2f, 2f);

          GameObject throwThis = Instantiate (projectile, transform.position + new Vector3(xRand, yRand, 0), transform.rotation) as GameObject;



To do this you need to take into account the rotation of the player, and transform your position to be relative to this. To do this I’m using the TransformVector method, to rotate my random position to be orthogonal to the player.

Note; I’m using the SerializeField attribute to expose the variables m_minDistance, m_maxDistance, and m_prefab. I’m also storing m_position and m_distance as instance variables attached to the script, to save on memory (not having to create a variable every time a new object is instantiated).

To generate the position of the new object, I’m simply using Random.Range to get the value for m_distance, and then Random.Range again to choose between left and right. The object is instantiated, and then on the next line positioned by adding the transformed position generated, to the position of the player.

public class OrthogonalInstantiate : MonoBehaviour
    private float       m_minDistance;
    private float       m_maxDistance;
    private GameObject  m_prefab;
    private float       m_distance;
    private Vector3     m_position;

    public void Update()
            if(m_position == null) m_position = new Vector3();

            m_distance = Random.Range(m_minDistance, m_maxDistance);

            if (Random.Range(0, 2) == 0)
                m_position.Set(-m_distance, 0f, m_distance);
                m_position.Set(m_distance, 0f, m_distance);

            //Set position of new object
            GameObject go               = (GameObject)GameObject.Instantiate(m_prefab);
            go.transform.position       = transform.position + transform.TransformVector(m_position);

I hope this helped you, let me know if there’s anything that doesn’t make sense.