user3012847
user3012847

Reputation: 51

Jquery moving an object in a circular path

i'm having a problem on moving an object in a circular path on scroll, the object keeps moving in zig zag. i have no idea on fixing this, i think my formula is incorrect. i used css translate to move the object. i hope you can help me to fix my code, all the rotation happen on scroll, here's my code:

<html>
    <head>
        <style>
            body { 
                height: 20000px; 
            }

            .tarz {
                width: 50px;
                height: 50px;
                background: #F00 ;
                position: fixed;
            }

        </style>

        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script type="text/javascript">

            $(document).ready(function() {

                window.objYFlag = "down";
                window.objXFlag = "right";
                window.objY = 0;
                window.objX = 50;
                window.objYMax = 50;
                window.objXMax = 50;

                $(window).scroll(function() {

                    var scroll = $(document).scrollTop();

                    window.objX = ( 50 - (window.objY - scroll) + window.objX ); 
                    //formula for x

                    if (window.objY === window.objYMax) {
                        window.objYFlag = "up";
                    }

                    if (window.objY === 0) {
                        window.objYFlag = "down";
                    }

                    if (window.objYFlag === "down") {
                        window.objY = window.objY + 1;
                    } else {
                        window.objY = window.objY - 1;
                    }

                    console.log(window.objX + ' ' + window.objY);
                    $('.tarz').css('transform', 'translate(' + window.objX + 'px,' + window.objY + 'px)');

                });

            });
        </script>
    </head>
    <body>
        <div class="tarz"></div>
    </body>
    <html>

Thanks guys, i hope you can help me. :)

Upvotes: 1

Views: 1271

Answers (1)

Blazemonger
Blazemonger

Reputation: 92893

Time to review your trigonometry. Was this what you wanted to accomplish?

 $(window).scroll(function () {
     var scroll = $(document).scrollTop();
     window.objX = 50+100*Math.cos(scroll/25);
     window.objY = 50+100*Math.sin(scroll/25);
     $('.tarz').css('transform', 'translate(' + window.objX + 'px,' + window.objY + 'px)');
 });

http://jsfiddle.net/mblase75/waLK9/

Fiddle with the numbers to get the desired speed and position.

Upvotes: 2

Related Questions