# Random vector within range

This topic is 4965 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

im trying to write a particle engine but im stuck on this one part. i need to create a function that can create a random vector, within a certain range, to initialize a particle. say for example there is a spread of 90 degrees, around the normal, that the particle's direction can point. i cant figure out how to get a vector to initialize within a certain angle. once i find that random vector i just make that the velocity (speed and direction) of the particle. make sense?

##### Share on other sites
maybe you could translate the normal to some spherical representation and then add random values inside a certain range to the angles, before transforming it back to cartesian coordinates ?

##### Share on other sites
This thread was also about generating unit vectors, only this time the vectors were also allowed to point downwards (i.e. vectors in the unit sphere). However you can simply discard the negative directions. It also mentions how to do it angle-based.

Greetz,

Illco

##### Share on other sites
ok ive been playing with my engine alot and i decided to go with using random angles and then convert them to vectors. im using this code:
float sp = speed;//random anglefloat xy = rand()%(int)spread-(spread*0.5);	//spread on XY planefloat zy = rand()%(int)spread-(spread*0.5);	//spread on ZY planefloat x = sin(xy);float y = cos(xy);float z = sin(zy);if(y<0) 	y*=-1;Vector3 vect = Normalize(x, y, z);pArray[part].dir.x = vect.x * sp;pArray[part].dir.y = vect.y * sp;pArray[part].dir.z = vect.z * sp;

the problem is when i set the spread to any angle between 1 and 179.5 i always get the same effect. the particles dont constrain to the range and exist everywhere above the xz-plane. does anybody see the problem in my code?

p.s. im aware that "float sp" is redundant but i plan to add speed variation later and im going to put it there.

##### Share on other sites
If this is stupid, I apologize, but are you converting to radians before calling the trig functions? I just ask because you give the range in degrees in your post.

Also, is there any particular reason you don't just use the spherical representation directly, i.e.:

float x = sin(xy)*cos(zy);
float y = cos(xy)*cos(zy);
float z = sin(zy);

Just curious (you may very well have a good reason for doing it the way you're doing it).

##### Share on other sites
im only inputting degrees and there is no conversion to radians. could that be the problem?

EDIT: not converting the degrees into radians WAS the problem. woohoo!!! thanks for the help. soon i think ill post some screens of my particle engine!

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 14
• 14
• 45
• 22
• 27
• ### Forum Statistics

• Total Topics
634044
• Total Posts
3015210
×