본문 바로가기

언어/javascript

javascript : 회전시키기

반응형

천체의 움직임을 표현하기위해서 삼각함수를 사용한다.

 

 

@ = 태양

O = 지구

* = 달 

 

이라고 가정했을때 수식을 작성한다.

<body>
    <h1 id="sun">@</h1>
    <h1 id="earth">O</h1>
    <h1 id="moon">*</h1>

    <script>
        window.onload = function () {
            var sun = document.getElementById('sun');
            var earth = document.getElementById('earth');
            var moon = document.getElementById('moon');

            // 문서 객체의 스타일 속성을 변경합니다.
            sun.style.position = 'absolute';
            earth.style.position = 'absolute';
            moon.style.position = 'absolute';
            sun.style.left = 250 + 'px';
            sun.style.top = 200 + 'px';

            var earthAngle = 0;
            var moonAngle = 0;

            // 애니메이션을 시작합니다.
            setInterval(function () {
                // 각도로 지구와 달의 좌표를 구한다.
                var earthLeft = 250 + 150 * Math.cos(earthAngle);
                var earthTop = 200 + 150 * Math.sin(earthAngle);
                var moonLeft = earthLeft + 50 * Math.cos(moonAngle);
                var moonTop = earthTop + 50 * Math.sin(moonAngle);

                // 위치 이동
                earth.style.left = earthLeft + 'px';
                earth.style.top = earthTop + 'px';
                moon.style.left = moonLeft + 'px';
                moon.style.top = moonTop + 'px';

                // 각도를 변경합니다.
                earthAngle += 0.1;
                moonAngle += 0.3;
            }, 1000 / 30);
        };
    </script>

</body>

 

소스코드는 어렵지 않다 기본적이 삼각함수를 이용해서 움직임을 1초에 30번식 바꾸도록 표현한다.

먼저 태양을 중심으로 각도를 이용해서 좌표를 구하고

지구를 중심으로 각도를 이용해서 달의 좌표를 구한다. 

앵글의 속도는 달이 지구가 돌아가는것보다 3배 빠르다 

반응형