html
1<!doctype html> 2 <html> 3 <head> 4 <title>breakout</title> 5 <meta charset="utf8"> 6 <style> 7 canvas { 8 9 background: #eee; 10 display:block; 11 margin:auto 0 ; 12 13 } 14 </style> 15 </head> 16 <body> 17 <h1>breakout</h1> 18 <hr> 19 20 <canvas id="mycanvas" width="500" height="400"></canvas> 21 22 <script> 23 // canvasを準備する 24 var canvas = document.getElementById("mycanvas"); // canvasを操る変数を取得する 25 var ctx = canvas.getContext("2d"); // 2Dグラフィクスを描くためのオブジェクトを取得する 26 27 // ボールを表すオブジェクトを作る 28 var ball = { 29 x: 300, // x座標 30 y: 100, // y座標 31 radius: 20, // 半径 32 dx: 5, 33 dy: 5 34 } 35 // ボールを描く関数 36 function drawBall() { 37 ctx.beginPath(); 38 ctx.arc( ball.x, ball.y, ball.radius, 0, Math.PI*2 ); // (x座標、y座標、半径、角度1、角度2) 39 ctx.fillStyle = "#ff0000"; 40 ctx.fill(); 41 ctx.closePath(); 42 43 44 } 45 function moveBall(){ 46 47 ball.x += ball.dx; 48 } 49 50 function collisionDetector(){ 51 52 if( ball.x >= canvas.width){ 53 54 ball.dx *= -1; 55 56 } 57 58 if(ball.x <= 0){ 59 60 ball.dx *= -1; 61 } 62 63 } 64 65 66 // ↓ 描く処理をまとめた関数。この中に全ての処理を入れる。 67 function draw() { 68 ctx.clearRect( 0, 0, canvas.width, canvas.height ); 69 70 drawBall(); 71 moveBall(); 72 collisionDetector(); 73 74 } 75 76 setInterval( draw, 10 ); // 10ミリ秒間隔で描き続ける(draw関数を繰り返し実行する) 77 </script> 78 </body> 79 </html>
上記のコードでは、ボールの位置(中心の座標)が壁の位置に来たら「反射する」、という状況であり、ボールが壁に半分くらいめり込んでから反射するという状況らしいのですが、意味が分からない部分があります。
そもそも中心の座標というのは、どこを指すのでしょうか?また、ボールが壁に触れた瞬間に、ボールを反射させる為のコードを書きたいと思っているのですが、そのヒントのようなものを頂くことはできますでしょうか...?
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。