0

Hey Guys Canvas の JavaScript で問題が発生しています。基本的に、ボールをジグザグに移動させる方法がわかりません。私は JavaScript に不慣れで、まだ学んでいるので、どなたか助けていただければ幸いです。だから私の質問は、ボールをジグザグに移動させるにはどうすればよいですか? 現在、左から右への直線のみを実行します。

これが私のコードです

// JavaScript Document
window.addEventListener('load', eventWindowLoaded, false); 

function eventWindowLoaded() {
    canvasApp(); 
}

function canvasSupport () { 
    return Modernizr.canvas;
}

function canvasApp() {

    // test if Modernizr has been loaded
    if (!canvasSupport()) { 
        return; 
    }

    var pointImage = new Image(); 
    // put an image into an image object
    pointImage.src = "point.png"; 

    function drawScreen () {

        // fill the background
        context.fillStyle = '#EEEEEE';
        context.fillRect(0, 0, theCanvas.width, theCanvas.height);
        // Draw  a Box around the fill
        context.strokeStyle = '#000000';
        context.strokeRect(1, 1, theCanvas.width - 2, theCanvas.height-2);

        // Create ball

        if (moves > 0 ) { 
            moves--; 
            ball.x += xunits; 
            ball.y += yunits;
        }

        // Draw points to illustrate path

        points.push({
            x: ball.x,
            y:ball.y
        });

        // for loop with drawImage inside the loop to draw the points

        for (var i = 0; i < points.length; i++) { 
            context.drawImage(pointImage, points[i].x, points[i].y, 1, 1);
        }
        context.fillStyle = "#000000"; 
        context.beginPath();
        context.arc(ball.x, ball.y, ball_radius, 0, Math.PI * 2, true);
        context.closePath();
        context.fill();
    }

    var speed = 10;
    // coordinates of the left hand point
    var p1 = {
        x: 20,
        y: 250
    }; 
    var p2 = {
        x: 480,
        y: 250
    };
    // distance between left and right x coordinates
    var dx = p1.x - p2.x; 
    var dy = p1.y - p2.y;
    // Calculate the distance between points
    var distance = Math.sqrt(dx * dx + dy * dy);
    var moves = distance / speed;
    var xunits = (p2.x - p1.x) / moves;
    var yunits = (p2.y - p1.y) / moves;
    var ball = {
        x: p1.x, 
        y: p1.y
    };
    var points = new Array();
    var the_interval = 20
    var ball_radius = 5

    // save the context in a variable
    theCanvas = document.getElementById("canvasOne"); 
    context = theCanvas.getContext("2d");

    // call the drawscreen function every 33 miliseconds
    setInterval(drawScreen, the_interval); 

}

これを支援するためにModernizrを使用しています。

4

3 に答える 3

0

宿題のように聞こえます:-)とにかく、ここでSinを使用して解決策を見つけました。必要な正確な形状をより厳密に定義しなかったため、これを使用してジグザグを作成することは間違いなく悪い考えではありません。

(function () {
  var startPoint = { x: 0, y: 250 },
      endPoint = { x: 500, y: 250 },
      ball = { x: startPoint.x, y: startPoint.y },
      canvas = document.getElementById('canvas'),
      context = canvas.getContext('2d');

  window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       || 
              window.webkitRequestAnimationFrame || 
              window.mozRequestAnimationFrame    || 
              window.oRequestAnimationFrame      || 
              window.msRequestAnimationFrame     || 
              function( callback ){
                window.setTimeout(callback, 1000 / 60);
              };
    })();

  function draw() {

    var dx = endPoint.x - startPoint.x, 
        dy = endPoint.y - startPoint.y,
        a = (function () { if (dy !== 0) { return dx/dy; } else { return 0; }})(),
        b = startPoint.y - a*startPoint.x,
        y = function (x) { return a*x + b; };

    ball.x = ball.x + 1;
    ball.y = y(ball.x) + Math.sin(ball.x*0.1)*10;

    context.fillStyle = '#EEEEEE';
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.strokeStyle = '#000000';
    context.strokeRect(1, 1, canvas.width-2, canvas.height-2);

    context.fillStyle = "#000000"; 
    context.beginPath();
    context.arc(ball.x, ball.y, 5, 0, Math.PI*2, true);
    context.closePath();
    context.fill();

    window.requestAnimFrame(draw);
  }

  window.requestAnimFrame(draw);

})();

Yでジグザグに動くだけですが、このアイデアを使用して、XとYの両方で独自の「偏差」を追加または変更できます。Modernizrを追加してキャンバスを検出することもできますが、この質問では無関係だと思います。お役に立てば幸いです;-)ここで試すことができます-> http://jsbin.com/ahefoq/1 <-。楽しみ!

mz

于 2013-02-28T09:17:46.703 に答える
0

数学関数に夢中になるまで書くのではなく、サイン波を「ジグザグ」として使用することをお勧めします。http://www.w3schools.com/jsref/jsref_sin.aspまたはhttps://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/sinを確認してください

于 2013-02-26T10:09:11.997 に答える
0

質量と跳ね返り係数に基づいて、ボール同士の衝突の速度と方向を計算します

     -Your answer can be found in there. The problem with your original code was that you calculated the total change in distance over the total time. If the zig zag is going to move left to right at a 45 degree angle then the absolute value of the speed of |y| == x. create a listener or loop to switch the value of y from positive to negative values depending when you want to zig or zag. check out that older post it should clear things up
于 2013-02-26T11:50:13.070 に答える