Make blood particles go in Random direction?

    I am pretty bad at math but I wish to learn soon enough. My question is right now how I would get a random direction for my blood particles to travel. Here is my Blood class :
public class Blood {
	private int x, y, direction, speed = 3, delta = 0;
	private boolean isCompleted = false;

	public Blood(int x, int y){
		this.x = x;
		this.y = y;
		direction = (int) ((Math.random() * 360) % 360);
	}
	public void render(Graphics g){
		g.pushTransform();
		g.setColor(new Color(255, 0, 0, 255));
		g.fillRect(x, y, 2, 2);
		g.popTransform();
	}
	public void update(){
		delta += 1;
		
		if(delta >= 10){
			destroy();
		}
		x += direction+speed;
		y += direction+speed;
	}
	public void destroy() {
		isCompleted = true;
	}
	public boolean getCompleted(){
		return isCompleted;
	}
}
 This is handled by a Blood Emitter class that has an array of blood and what not, but that is not what I am asking anyways. How would you get the random direction for the blood to go?

In blood emitter, create

Random r = new Random();

Then I’d change the constructor…

public Blood(int x, int y, int xvel, Random r)

You need to chose an appropriate speed for your game, so with an xVelocity and a yVelocity, lets say between -4 and +4

float xvel = r.nextInt(9)-4; //this would give a random number between 0-8 (inclusive), so -4 to get it into the chosen range
float yvel = r.nextInt(9)-4;

You might want to check xvel and yvel arn’t both == 0, else it wont move. I’d probably not worry though it’d rarely happen and you’ll have so many it wont matter.

Then, in update, simply do as you do

x += xvel;
y +=yvel;

And then to reduce speed slowly
xvel*=0.9f;
yvel*=0.9f;

Or some similar value… just my idea.

(You’d need to change x and y to floats for this - but you can change all the values to ints and use higher numbers, or not reduce the velocity, or whatever you want)

Thanks for the reply! I will most certainly test this out! Waiting for someone to answer I actually sort of made my own blood explosion thing. It’s just a growing square, but it is certainly entertaining for the eye!

Any particle’s velocity can be implemented with a vector, as it seems you started to do.

NewPosition = Position + Velocity ( x Time)

Good enough random velocity: (range on each axis: negative to positive MAX_SPEED)


velX = (int) (Math.random() * MAX_SPEED * 2 - MAX_SPEED);
velY = (int) (Math.random() * MAX_SPEED * 2 - MAX_SPEED);

Forget angles.

Your code worked perfectly for what I wanted, thank you! ;D ;D ;D ;D ;D