Skip to content

Instantly share code, notes, and snippets.

@LB-Digital
Created July 4, 2018 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LB-Digital/46dc4c46b98a1ce2f8983f82dbd792b2 to your computer and use it in GitHub Desktop.
Save LB-Digital/46dc4c46b98a1ce2f8983f82dbd792b2 to your computer and use it in GitHub Desktop.
Generate a random X,Y component vector with a magnitude in a given range
// Minimum & Maximum values for the speed of the vector
var minSpeed = 5;
var maxSpeed = 20;
// Random vector components in range -1,1
var randX = (Math.random()*2)-1;
var randY = (Math.random()*2)-1;
// Get magnitude of the random vector
var mag = Math.sqrt(Math.pow(randX,2) + Math.pow(randY,2));
// Use magnitude to normalise the vector components
var normX = randX/mag;
var normY = randY/mag;
// Get a random speed for the particle in range min,max
var speed = Math.random()*(maxSpeed-minSpeed) + minSpeed;
// Get final vector components in random direction of random speed in range min,max
var xVelocity = normX*speed;
var yVelocity = normY*speed;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment