Javascript - 画布,如何使球在Z字形中旅行

时间:2013-02-26 09:42:23

标签: javascript modernizr

嘿伙计我在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来帮助我。

3 个答案:

答案 0 :(得分:0)

如果不把数学函数写成疯狂,也许使用正弦波作为“之字形”是个好主意。查看http://www.w3schools.com/jsref/jsref_sin.asphttps://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/sin

答案 1 :(得分:0)

Calculate velocity and direction of a ball to ball collision based on mass and bouncing coefficient

     -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

答案 2 :(得分: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来检测画布,但我认为在这个问题中它是无关紧要的。希望它有所帮助;-)你可以在这里试试 - &gt; http://jsbin.com/ahefoq/1&lt; - 。享受!

MZ