Search code examples
c#unity-game-enginerandom

Unity: Spawn an object within a predefined area


I am trying to instantiate and spawn an object in unity that's based on another's gameobject position(objA). Ideally, I would like the object to be spawned within a cricle section, with the center of the circle being at the objA. The object should be spawned "in front" of objA within a given area and that area will be a section of a circle with given radius and angle (see image for reference). Object should be randomly spawned at any position within the given dotted region

I have found the following:

     randomLocationWithinCircle = Random.insideUnitSphere * radius;
     transform.position = randomLocationWithinCircle + objA.transform.position;   

However, here, I am only controlling the radius, do you know how I can incorporate the desired angle information (alpha)? I couldn't find anything useful myself, only some examples with giving whole maps, which is overcomplicated for this case.

Thanks in advance!

Edit: objA is non-stationary, hence I cannot in advance state the absolute area, it's relative to position of objA


Solution

  • This is the forward and upward vector of the objA. NB both are normalized.

    var fwd = objA.transform.forward;
    var up = objA.transform.up;
    

    This is a quaternion that can rotate a vector randomAngle degrees around the objA's upward vector.

    var rot = Quaternion.AngleAxis(randomAngle, up);
    

    Now you can rotate the objA's forward vector with this quaternion. NB the rotated vector is still normalized.

    var rotatedVec = rot * fwd;
    

    Then multiply the vector with a random number to randomly scale it.

    var finalVec = rotatedVec * randomNumber;
    

    Finally you can add this vector to the objA's position to get a random in-front position of the objA.

    transform.position = objA.transform.position + finalVec;