Karz
Karz

Reputation: 557

Unity 3D Set object in cone

I'm looking to place an object at a specific position relative to another :

enter image description here

This new object has to be placed in the pink zone, and I only know the minimum and max distance of placement, an angle relative to my first object forward direction (maxAngle in degrees), and the position of this first object.

I already know how to check if an object is placed in the pink zone, but not set its position in this zone. So I took the code to check an object in the cone, but I can't get how to transform it to set the position in the cone.

float distance = Random.Range(minDistance, maxDistance);
float angle = maxAngle *= Mathf.Deg2Rad;
float coneRadius = distance * Mathf.Tan(angle);

Vector3 vect = firstObject.transform.position - targetObject.transform.position;
targetObject.transform.position = new Vector3(angle, 0, firstObject.transform.position.z + distance);

If you can give me clues, it'll be very cool.

Upvotes: 2

Views: 1205

Answers (1)

Fattie
Fattie

Reputation: 12336

The trick is to move the local position and then straighten...

This is indeed a basic technique in Unity or any transform-based scene engine.

Create the new object, "newb".

(1) Position the object exactly at the "+" in your image.

(2) Choose your angle

   angle = Random.Range(-maxAngle, maxAngle);

(3) Twist newb by that much:

   newb.transform.eulerAngles = new Vector3( 0f, 0f, angle);

(4) Choose your distance:

     distance = Random.Range(minDistance,maxDistance);

(5) Then offset the LOCAL position of newb by that much:

     newb.transform.Translate(0f, 0f, distance, Space.Self);

And then the trick:

Note that "newb" will be "twisted", so make it sit straight:

       newb.transform.eulerAngles = Vector3.zero;

Upvotes: 3

Related Questions