summaryrefslogtreecommitdiff
path: root/web/simu/gravity.html
blob: 8ea6df58a4bf427022c5a5338f825e773006b6cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<html lang=en>
<head>
<meta charset=utf-8>
    <title>Javascript gravity</title>
    </head>
    <body onload="init()">


<script>
        var canvas, ctx, container;
         canvas = document.createElement( 'canvas' );
          ctx = canvas.getContext("2d");
    var ball;
    var message = "gravity simulator";


    // Velocity x
     var vx = 5.0;
    // Velocity y - randomly set
    var vy;

    var gravity = 0.5;
    var bounce = 0.7;
    var xFriction = 0.1;

    function init(){
       setupCanvas();
      vy = (Math.random() * -15) + -5;
        ball = {x:canvas.width / 2, y:100, radius:20, status: 0,   color:"red"};

    }//end init method

    function draw() {
        ctx.clearRect(0,0,canvas.width, canvas.height);
        //display some text
	       ctx.fillStyle = "blue";
           ctx.font = "20px Arial";
           ctx.fillText(message, 20,20);



             //draw cirlce
            ctx.beginPath();
            ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI*2, false);
            ctx.fillStyle = ball.color;
            ctx.fill();
            ctx.closePath();

        ballMovement();

    }

    setInterval(draw, 1000/35);




    function ballMovement(){
        ball.x += vx;
        ball.y += vy;
        vy += gravity;

        //If either wall is hit, change direction on x axis
        if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0){
            vx *= -1;
        }

          // Ball hits the floor
        if (ball.y + ball.radius > canvas.height){// ||

            // Re-positioning on the base
           ball.y = canvas.height - ball.radius;
            //bounce the ball
              vy *= -bounce;
            //do this otherwise, ball never stops bouncing
              if(vy<0 && vy>-2.1)
                         vy=0;
            //do this otherwise ball never stops on xaxis
             if(Math.abs(vx)<1.1)
                 vx=0;

             xF();

    }


    }

    function xF(){
             if(vx>0)
                 vx = vx - xFriction;
             if(vx<0)
                 vx = vx + xFriction;
    }






     function setupCanvas() {//setup canvas


	container = document.createElement( 'div' );
	container.className = "container";

	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
	document.body.appendChild( container );
	container.appendChild(canvas);

	ctx.strokeStyle = "#ffffff";
	ctx.lineWidth =2;
}

        </script>
    </body>
</html>