【问题标题】:Can't get sprite to move in a circle path无法让精灵在圆形路径中移动
【发布时间】:2016-04-22 09:45:54
【问题描述】:

我有一个名为 snitch 的精灵,我试图让它在一个圆圈中移动,中心在 canvas/2(画布被命名为空间)和半径 30。我正在使用以下代码,但它没有似乎什么也没做,“告密者”只是站在那里,在坐标 (0,0) 上什么也不做。我尝试从 MySprite2 函数中删除这些 (0,0) 坐标,但是当我这样做时,飞贼甚至都没有出现。

var ctx = space.getContext("2d"); 
var FPS = 40;
var snitch= new MySprite2("http://i.imgur.com/IgNKTbW.png");

function MySprite2 (img_url) {
  var x = this.x = 0;
  var y = this.y = 0; 
  this.visible= true;
  var img = this.MyImg2 = new Image();
  this.MyImg2.src = img_url;
}

MySprite2.prototype.Do_Frame_Things = function() {
  if (this.visible) ctx.drawImage(this.MyImg2, this.x, this.y);
}; 

function Do_a_Frame () {
  ctx.clearRect(0, 0, space.width, space.height);
  snitch.Do_Frame_Things();
}

function theMoves(snitch){
  var theta = 0;
  for (theta = 0; theta < 2 * Math.PI; theta+=0.1) { 
     snitch.x = (space.width/2) + Math.sin(theta)*30;
     snitch.y = (space.height/2) + Math.cos(theta)*30;
  }
}
setInterval(theMoves, 1000/FPS);
setInterval(Do_a_Frame, 1000/FPS);

知道有什么问题吗? 好的,它在移动,但现在它只是在一条直线上运行,而不是一个圆圈。下面是新代码。

function MySprite (img_url) {
  var x = this.x = (space_x/2);
  var y = this.y = (space_y/2);
  var angle = this.angle = 0;
  this.visible= true;
  var img = this.MyImg = new Image();
  this.MyImg.src = img_url;
}

MySprite.prototype.Do_Frame_Things = function() {
  if (this.visible) ctx.drawImage(this.MyImg, this.x, this.y);
};  

function theMoves(){
  snitch.x += Math.cos(snitch.angle)*2;
  snitch.y += Math.sin(snitch.angle)*2;
}
setInterval(theMoves, 40);

【问题讨论】:

    标签: javascript animation canvas path geometry


    【解决方案1】:

    我看到的第一个错误是您的 sin 函数将返回 undefined,因为您需要使用以下语法调用它:

     Math.sin()
    

    第二个错误是你的告密者变量未定义。错误是由以下代码行引发的。

     snitch.x = (space.width/2) + Math.sin(theta)*30;
    

    您的第三个错误是:

    snitch.y = (space.height/2) + cos(theta)*30;
    

    我创建了一种更加模块化的方法来帮助您制作圆形动画。

    现场演示:http://codepen.io/larryjoelane/pen/obGPwY

    html:

         <canvas width ="500" height="500" id="canvasOne"></canvas>
    

    JavaScript:

     var canvas = new Canvas("canvasOne");
    
     var thisCanvas = canvas.instance("canvasOne");
    
     var imageURL = "http://bytewarestudios.com/assets/images/sphere.png";
    
     var image = canvas.createImage(imageURL);
    
     var context = canvas.context2D("canvasOne");
    
     /* Formula to determine x and y points on the circumference of a    
      * circle
      * cx and cy = (origin or center of the circle)
      * r = radius of the circle
      * a = angle in radians(360deg = 6.285714285714285714285714285714 radian) or 2 * PI
      *  Formulas examples below for x and y points
      *   var x = cx + r * Math.cos(a);
      *   var y = cy + r * Math.sin(a);
      */
    
     //initialize the degree variable
     var deg = 0;
    
     //frames per second
     var fps = 45;
    
     window.requestAnimationFrame(drawCircle); // start the animation
    
     function drawCircle() { //begin function
    
       setTimeout(function() {
    
         //increment the degrees
         deg = deg + 1;
    
         //used to offset the circle radius to bring the circle in from the border of 
         //the canvas
         var offset = 120;
    
         //radius of the circle
         var r = ((thisCanvas.width - offset) / 2);
    
         //x coordinate of the circle origin
         var cx = ((thisCanvas.width) / 2);
    
         //y coordinate of the circle origin
         var cy = ((thisCanvas.height) / 2);
    
         //store the angle in radians
         var a = canvas.toRadians(deg);
    
         var x = cx + r * Math.cos(a);
         var y = cy + r * Math.sin(a);
    
         //clear the canvas  
         context.clearRect(0, 0, thisCanvas.width, thisCanvas.height);
    
         //draw the first image
         context.drawImage(image, x, y);
    
         //start the animation
         window.requestAnimationFrame(drawCircle);
    
       }, 1000 / fps);
    
     } //end function
    
     function Canvas() { //begin canvas constructor    
    
       Canvas.prototype.createImage = function(imageURL) {
    
         //create a new image
         var image = new Image();
    
         //set the image source
         image.src = imageURL;
    
         //return the image object
         return image;
    
       };
    
       Canvas.prototype.context2D = function(id) {
    
         var canvas = document.getElementById(id);
    
         var context = canvas.getContext("2d");
    
         return context;
    
       };
    
       Canvas.prototype.instance = function(id) {
    
         var canvas = document.getElementById(id);
    
         return canvas;
    
       };
    
       Canvas.prototype.toRadians = function(angle) {
    
         return angle * (Math.PI / 180);
    
       };
    
     } //end canvas constructor
    

    【讨论】:

    • 是的,在我的代码上更新了它,它仍然没有移动。
    • 好吧,我还在解决它,我会告诉你我还有什么想出的
    • 想我明白了。添加了 snitch.angle +=0.1;在新代码中,它会循环运行。
    【解决方案2】:

    很多问题,所以我做了一个重写。已经完成并解释了我做了什么以及我为什么这样做。

    第一行一切都好,但不需要 FPS,因为这将由浏览器决定。对于游戏,除非您拥有专用硬件和确定性操作系统,否则您永远无法保证任何帧速率。只有专用游戏机提供此功能。

    var ctx = space.getContext("2d"); 
    

    使用new 和prototypes 不利于游戏设计,因为它们会产生大量不必要的额外开销。事实上,完全避免使用这种类型的构造函数通常是个好主意。

    使用生成器函数,不要直接接触原型

    在变量开头的 Javascript 大写的生成器 BTW 之前先声明你的方法,这是为类类型对象保留的,但这是个人风格选择而已

    // draw the sprite is visible
    var doFrameThings = function() {
        if (this.visible) { // though you don't have to put the curly braces here
                            // you should make it a habit  to always use them
            ctx.drawImage(this.myImg , this.x, this.y);
        }
    }; 
    

    创建一个更新精灵的函数,如果帧速率下降,则使用最后一帧时间来确保一致的速度

    var updateSprite = function(frameTime){
        this.theta += this.deltaTheta * frameTime;
        this.x = (space.width/2) + Math.sin(this.theta)*30;
        this.y = (space.height/2) + Math.cos(this.theta)*30;
    }
    

    创建一个精灵。这种方法与原型方法几乎没有区别,但它提供了更好的性能

    function createSprite(imgURL){
        var sprite = {  // create the sprite
            x:0,
            y:0,
            theta: 0,
            deltaTheta: Math.PI/40,
            visible:false,           // not visible until it has loaded.
            draw : doFrameThings,    // add the draw function
            update : updateSprite,   // add the update function
            myImg : (function(){     // call a annon function that creates the 
                                     // image returning it to myImg
                var image = new Image();
                image.src = imgUrl;
                image.onload = function(){  // flag it as visible only when it has loaded.
                    sprite.visible = true;
                };
                return image;
            })()
        };
        return sprite; // return the created sprite
                       // this is exactly the same as new does except new returns
                       // this instead of the named object.
    }        
    

    创建一个精灵。现在,您不必调用使用 New 和参与原型系统的所有开销。

    var snitch = createSprite("http://i.imgur.com/IgNKTbW.png");
    

    使用setInterval 是一种非常糟糕的动画制作方式。首先,您有两个 setInterval ,它们将不同步,并且不能保证它们会在请求的时间间隔内发生。它们也不会与显示硬件同步,所以你会得到剪切。此外,由于它们没有与浏览器的渲染系统同步,您可能会出现闪烁或更糟的情况。

    如果你的渲染时间超过了间隔,它最终会导致你的应用程序崩溃,并且没有简单的方法可以知道是否发生这种情况

    所以永远不要使用setInterval。个人切勿将setInterval 用于任何危险的方法,应从 Javascript 中删除。

    使用requestAnimationFrame 获得稳定的 60 fps 并同步到显示硬件和浏览器的渲染系统。因为它与显示器同步,所以帧之间的时间将以大约 1/60 秒为单位。如果您错过了第一帧,您将不得不等待下一次刷新,刷新时间为 1/60 秒。

    创建一个主循环/更新函数并从同一个函数调用所有动画。

    var lastTime = new Date().valueOf();  // for tracking the frame time
    function update(time){  // requestAnimationFrame provides the current time
        var frameTime = time-lastTime;
        // clear the canvas
        ctx.clearRect(0, 0, space.width, space.height);
    
        snitch.update(frameTime); // update sprite
        snitch.draw(); // draw the sprite
    
    
        requestAnimationFrame(update); // request the next animation frame
        lastTime = time;  // save the time this frame was called 
    }
    
    requestAnimationFrame(update); // start the animation
    

    这应该可以让告密者顺利进行。

    【讨论】:

      【解决方案3】:

      Moves 函数上有一个告密参数。当它被不带参数的间隔刻度调用时,它作为一个未定义的对象妨碍了它。

      如果要全局使用,只需删除参数即可。

      或者你可以这样做

      setInterval(function(){theMoves(snitch)}, 1000/FPS);

      【讨论】:

      • 当然,如果您使用的是画布;你应该清除然后每帧重绘它。这就是它的工作方式。
      • 把它放在那里:ctx.clearRect(0, 0, space.width, space.height);
      • 好吧,看来你没有调用它,但只调用了一次。
      • 哦该死的,你是对的!添加 setInterval(Do_a_Frame, 1000/FPS);但仍然没有运气。
      • 您应该在位置计算后将其添加到Moves函数中。
      猜你喜欢
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多