Skip to content

Instantly share code, notes, and snippets.

Created July 4, 2018 20:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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