Frontend/JavaScript
[JavaScript] 이중 forEach문 주의
yjwoo
2023. 8. 18. 16:16
문제의 코드
update() {
missiles.forEach(missile => {
if (missile.direction === "vertical") {
this.vy = 1;
this.position.y += this.vy;
}
else if (missile.direction === "horizontal") {
this.vx = 1;
this.position.x += this.vx;
}
});
this.blockCollisionCheck();
}
일정한 속도로 미사일을 쐈으면 좋겠는데 의도치 않게 가속도가 붙었다.
뭐지... 혹시 또 forEach문 때문일까 했는데 역시나였다!!^^ 편하다는 이유로
for문 대신 forEach문 정말 많이 썼는데 아래 코드 때문에 문제가 생긴 것이었다.
function render() {
...이하 생략
missiles.forEach((missile) => {
missile.update();
missile.draw();
});
}
main.js의 render 함수에서 missiles 배열에 있는 모든 미사일을 그리는데,
render에서 이미 forEach문을 썼기 때문에 이중 forEach문이 되었고
this.position.y 값에 missile 수 만큼의 값을 줬기 때문에 가속도가 붙은 것.
원하던 바는 아니었지만 가속도를 이용하고 싶을 때 쓸 수도 있지 않을까? (창조경제)
해결
update() {
if (this.direction === "vertical") {
this.vy = 1;
this.position.y += this.vy;
}
else if (this.direction === "horizontal") {
this.vx = 1;
this.position.x += this.vx;
}
this.blockCollisionCheck();
}
forEach문이 아닌 생성된 개별 미사일에 속도 주고 render에서 그리기
게임 개발은 좌표 싸움이라더니 정말이다. x좌표 y좌표 움직이기가 다인데 그게 단순한듯 하면서도 어려움
이번 달 안에 완성하고 🐶💩같은 코드 리팩토링 해야지 하하