ekeimaja Posted January 13, 2016 Share Posted January 13, 2016 So how can I set random speed for every object, so the acquired speed will stay? Now I have defined speed as constant, but it also increases the speed of every object. SPEED = 3; this.enemies.forEachAlive(function(enemy){ enemy.body.velocity.x += Math.random(SPEED + (SPEED/2)); }); I tried first with Tanks -example style, where is defined max and min speed, but i didn't work. Link to comment Share on other sites More sharing options...
AzraelTycka Posted January 13, 2016 Share Posted January 13, 2016 Hello, well I'd ask first what your Math.random(SPEED + SPEED/2) should do? Did you see any documentation for Math.random()? Just to be clear on this, Math.random() only returns random number from interval [0,1) where 1 is not included while zero is no matter what you put between it's parentheses (they should be actually left empty). Link to comment Share on other sites More sharing options...
chg Posted January 13, 2016 Share Posted January 13, 2016 It increases the speed because you are adding the new speed to the existing speed using the += operator. Link to comment Share on other sites More sharing options...
ekeimaja Posted January 13, 2016 Author Share Posted January 13, 2016 It was quick testing. First it was like this, but it did not work either. enemy.body.velocity.x += Math.random() * (SPEED + SPEED/20); Now I made it like this, but speed of objects increases and decreases all the time and they shake when moving. enemy.body.velocity.x = 10 + Math.random()* 500; Link to comment Share on other sites More sharing options...
chg Posted January 13, 2016 Share Posted January 13, 2016 Yes if you change the speed every frame (or every few frames) the speed will change every frame (or every few frames). If you want to set the speed and have it not change. Ummm.... don't change it! Link to comment Share on other sites More sharing options...
ekeimaja Posted January 13, 2016 Author Share Posted January 13, 2016 I want that every object of group has own constant speed, which is set with random. That is all I want to get done. Link to comment Share on other sites More sharing options...
chg Posted January 13, 2016 Share Posted January 13, 2016 7 minutes ago, ekeimaja said: Now I made it like this, but speed of objects increases and decreases all the time and they shake when moving. enemy.body.velocity.x = 10 + Math.random()* 500; ^ this code sets a constant speed for the particular enemy's physics body; (assuming 0 accelleration and no collision) the enemy object will only change speed if you run this line again (or run a line like it) Link to comment Share on other sites More sharing options...
ekeimaja Posted January 13, 2016 Author Share Posted January 13, 2016 Now I set speed in creating objects and now it works as it should. this.enemy.body.velocity.x = 50 + Math.random()* 800; Link to comment Share on other sites More sharing options...
Recommended Posts