Generate a random X,Y component vector with a magnitude in a given range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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