TIL: Typescrypt 공 튕기기.. (3) 공 겹침 현상 해결 - 220803

Lumpen·2022년 8월 4일
0

TIL

목록 보기
106/242

공의 경로가 상대 공의 부피에 닿으면
공이 겹쳐지면서 각이 서로 다른 방향으로 갈 때 까지 브루스를 추는 현상 발생하였다..

조금 어색하지만 해당 상황에는 서로 현재 날아오던 방향과 반대 방향의 각도로 날아가기로 했다

// class Ball 

  calcualateDistance(aa: Ball, ab: Ball) {
    const distancX = Math.pow(aa.x - ab.x, 2);
    const distancY = Math.pow(aa.y - ab.y, 2);

    const After = {
      MoveBetween: Math.sqrt(distancX + distancY),
      Between: ab.radius + this.radius,
    };

    return { After };
  }



  bounceBall(ab: Ball) {
    const { After } = this.calcualateDistance(this, ab);

    const thisAngle = this.ballAngle(this);
    const abAngle = this.ballAngle(ab);

    if (
      After.MoveBetween <= After.Between + 4 &&
      After.MoveBetween - After.Between > -4
    ) {
      const { newX, newY } = this.calculateAngle(thisAngle, abAngle);

      const ifX = this.x + newX;
      const ifY = this.y + newY;
      const distancX = Math.pow(ifX - ab.x, 2);
      const distancY = Math.pow(ifY - ab.y, 2);
      const MoveBetween = Math.sqrt(distancX + distancY);

      if (After.MoveBetween > MoveBetween) {
        const thisX = ifX - (ifX + this.vx);
        const thisY = ifY - (ifY + this.vy);
        const radian = Math.atan2(thisY, thisX);
        const degree = (radian * 180) / Math.PI;

        const newDeg = this.reverseAngle(degree);
        const { newX, newY } = this.calculateAngle(newDeg, abAngle);
        this.vx = newX;
        this.vy = newY;
      } else {
        this.vx = newX;
        this.vy = newY;
      }
    }
  }

해당 공의 새로 측정된 경로에 상대 공이 있을 경우
두 공 사이의 거리가 좁아지는 것이기 때문에
좁아질 경우 각도를 반대로 변경하는 식으로 공이 겹치는 버그를 해결하였다

현재는 calcualateDistance()에서 Ball을 받아서
처리하다보니 코드 재활용을 못했는데
x, y 좌표를 받는 것으로 변경하면 재활용이 가능할 것 으로 보인다..

각도가 간혹 부자연스러운 경우가 있어서 각도를 변경하는 식도 다시 생각해봐야 한다

profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글