1
\$\begingroup\$

My progress so far: https://codepen.io/anon/pen/OjxLeO

Currently the player has only x and y coordinates.

I want to change that to vectors, like described in http://natureofcode.com/book/chapter-1-vectors/

Let's say the player should start at 12:00 and move clockwise 1 degree per second.

No clue how to implement it.

Any hints?

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

You can use trigonometry to get the next position of the player with the formulas

x = cos(angle)
y = sin(angle)

where angle is the angle in radians (0 is 3:00 and it goes counter-clockwise in the positive direction).

If you have a variable called time which stores the current seconds, then to get the position at that time you need to use

x = cos(pi / 2 - time * pi / 180)
y = sin(pi / 2 - time * pi / 180)
\$\endgroup\$
0
0
\$\begingroup\$

Let me show you this with HTML and Javascript, so you can run in in your browser:

<!DOCTYPE html>
    <html>
        <head>
            <title></title>
            <style>
                html, body{
                    margin:0px;
                }
                canvas {
                    display: block;
                }
            </style>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head> 
        <body>
            <canvas id="canvas"></canvas>
            <script type="text/javascript" src="main.js"></script>
        </body>
</html>

THis is the javascript

window.onload = function () {

    var canvas = document.getElementById("canvas"),
        context = canvas.getContext("2d"),
        width = canvas.width = window.innerWidth,
        height = canvas.height = window.innerHeight;

    var centerX = height * .5,
        centerY = width * .5,
        radius = 200,
        xradius = 100,
        yradius = 300,
        angle = 0,
        speed = .01,
        x,y;

    render();

    function render(){

        context.clearRect(0,0,width,height);



        x = centerX + Math.cos(angle) * xradius; // Lenght of adjesant side of triangle
        y = centerX + Math.sin(angle) * yradius;

        context.beginPath();
        context.arc(x,y,10, 0, Math.PI * 2, false);
        context.fill();

        angle += speed; 
        requestAnimationFrame(render);
    }

}

If you have problems running this, try a newer version of Crome. You can just make an index.html file and a main.js and fill them with this content and open the html file in your browser.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .