[패스트캠퍼스] 챌린지 2일차 2.21

2023. 2. 22. 00:05개발 일지/패스트캠퍼스\챌린지

Part2. Canvas 챕터 01 - 5. 파티클에 가속도 주기 강의 시작!

이전 강의에서 Particle 안에 update함수를 정의 하여 파티클에 애니메이션 효과를 넣어 줬다. 이 애니메이션은 일정한 속도로 내려오게 되는데 이 효과를 빠르게 혹은 점점 느리게 시간에 따라 변화하는 방법에 대해 알아보는 시간이 된다.

우선 update 함수에서 속도에 일정한 값을 더 해줘서 가속도를 추가하는 작업을 한다.

...
class Particle {
...
	update() {
    	this.vy += 1;
        this.y += this.vy;
    }
}
...

이렇게 하면 점점 속도가 더 빨라져서 중력의 영향을 받는 느낌을 낼 수 있다. 좀더 자연스럽게 효과를 주기 위해서는 일정한 값을 더해주는 것이 아니라 일정한 값을 곱해주면 된다.

class Particle {
	constructor(x, y, radius, vy) {
    	this.x = x;
        this.y = y;
        this.radius = radius;
        this.vy = vy;
        this.acc = 1.03;
	}
    update() {
    	this.vy *= this.acc;
        this.y += this.vy;
    }
    ...
}

여기서 this.acc는 accelation의 약자이다.
이걸 지난 강의와 함꼐 활용을 하면 다양한 속도로 떨어지는 파티클 효과를 낼 수 있을 거 같다.
아래는 지난 강의를 활용하여 완성한 코드이다.

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const dpr = window.devicePixelRatio;

const canvasWidth = innerWidth;
const canvasHeight = innerHeight;

canvas.style.width = canvasWidth + 'px';
canvas.style.height = canvasHeight + 'px';

canvas.width = canvasWidth * dpr;
canvas.height = canvasHeight * dpr;
ctx.scale(dpr, dpr);

class Particle {
    constructor(x, y, radius, vy, acc) {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.vy = vy;
        this.acc = acc;
    }

    update(){
        this.vy *= this.acc;
        this.y += this.vy;
    }

    draw(){
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI / 180 * 360);
        ctx.fillStyle = 'orange';
        ctx.fill();
        ctx.closePath();
    }
}

const TOTAL = 5;
const randomNumBetween = (min, max) => {
    return Math.random() * (max - min + 1) + min;
}
let particles = [];

for (let i = 0; i < TOTAL; i++){
    const x = randomNumBetween(0, canvasWidth);
    const y = randomNumBetween(0, canvasHeight);
    const radius = randomNumBetween(50, 100);
    const vy = randomNumBetween(1, 5);
    const acc = randomNumBetween(0.5, 1.5);
    const particle = new Particle(x, y, radius, vy, acc);    particles.push(particle);
}

console.log(particles);

let interval = 1000 / 60;
let now, delta;
let then = Date.now();

function animate(){
    window.requestAnimationFrame(animate);
    now = Date.now();
    delta = now - then;

    if (delta < interval) return;

    ctx.clearRect(0, 0, canvasWidth, canvasHeight);

    particles.forEach(particle => {
        particle.update();
        particle.draw();

        if(particle.y - particle.radius > canvasHeight) {
            particle.y = -particle.radius;
        }
    });

    then = now - (delta % interval);
}

animate();

파티클 인스턴스들을 생성할 때, acc의 값을 랜덤으로 생성해서 acc의 값을 넣어주면 다양한 가속도의 파티클을 만들 수 있다.


http://bit.ly/3Y34pE0

 

패스트캠퍼스 [직장인 실무교육]

프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.

fastcampus.co.kr

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.