[p5] Random Walks

ChenΒ·2024λ…„ 6μ›” 17일
1

p5.js

λͺ©λ‘ 보기
1/5
post-thumbnail

random()

step()

1. 4 possible steps λ™μ„œλ‚¨λΆ 4λ°©ν–₯ (1~4)

step() {
    let choice = floor(random(4));
    if (choice === 0) this.x++;
    else if (choice == 1) this.x--;
    else if (choice == 2) this.y++;
    else this.y--;
  
	// ν™”λ©΄ λ„˜μ§€ μ•Šκ²Œλ”
    //this.x = constrain(this.x, 0, width - 1);
    //this.y = constrain(this.y, 0, height - 1);
}

2. 9 possible steps

step() {
    let xstep = floor(random(3)) - 1;
    let ystep = floor(random(3)) - 1;

    this.x += xstep;
    this.y += ystep;
}

3. 연속적인 μ‹€μˆ˜ (-1 to 1)

step() {
    let xstep = random(-1, 1);
    let ystep = random(-1, 1);

    this.x += xstep;
    this.y += ystep;
}


전체 μ½”λ“œ

function setup() {
    createCanvas(640, 360);
    walker = new Walker();
    background(127);
}

function draw() {
    walker.step();
    walker.render();
}

class Walker {
    constructor() {
        this.x = width / 2;
        this.y = height / 2;
    }

    render() {
        stroke(0);
        point(this.x, this.y);
    }

    step() {
        let choice = floor(random(4));
        if (choice === 0) this.x++;
        else if (choice == 1) this.x--;
        else if (choice == 2) this.y++;
        else this.y--;

        this.x = constrain(this.x, 0, width - 1);
        this.y = constrain(this.y, 0, height - 1);
    }
}
profile
ν˜„μ‹€μ μΈ λͺ½μƒκ°€

0개의 λŒ“κΈ€