0

我正在试验 Meteor 和 KineticJS。我正在尝试做的是创建一个形状,并将其移向舞台上的鼠标单击。该位置应保存到 mongoDB,以便可以更新所有连接的客户端。

我还没有走多远,但这就是我所拥有的。我基本上需要一种方法来做两件事:

  1. 如何使形状在舞台上向鼠标单击移动并在到达那里时停止?
  2. 除了我在下面尝试的 gameLoop 之外,还有更好的方法来检查形状的当前位置吗?它有效,但感觉不对。

谢谢!

//client.js code

var player = null;
var playerAnim = null;

Template.container.rendered = function () {

  var myCanvas = document.getElementById('myCanvas');
  var stage = new Kinetic.Stage({
        container: myCanvas,
        width: 1024,
        height: 1024
      });

      var layer = new Kinetic.Layer();

      // add the layer to the stage
      stage.add(layer);

      // add click listener for the stage
      $(stage.getContent()).on('click', function(evt) {
        //stage was clicked

        //Find the player shape in the database
        Players.find().forEach(function (dbShape) {
        player = new Kinetic.RegularPolygon(dbShape);

        // setup an animation to move the player to the right
          playerAnim = new Kinetic.Animation(function(frame) {

          var velocity = 50;
          var dist = velocity * (frame.timeDiff / 1000);
          player.move(dist, 0);
          Players.update(dbShape._id, {$set: {x: player.attrs.x, y: player.attrs.y}});
          }, layer);

          playerAnim.start();        
          layer.add(player);
          layer.draw();
        });
      });

    //make a gameLoop to check the position and stop the animation
    Meteor.setInterval(function(gameLoop){          
      if(player.attrs.x > 500){
        playerAnim.stop();
      }
    },  500);

    Meteor.autosubscribe(function () {
    // clear the canvas
    if (layer) {
      layer.removeChildren();
      layer.clear();
    }
    // populate the canvas with the Shapes collection
    Players.find().forEach(function (dbShape) {
      var player = new Kinetic.RegularPolygon(dbShape);

      layer.add(player);
      layer.draw();
    });
  });

}
4

1 回答 1

2
  1. 我会使用补间来做到这一点。抓取您的对象,获取鼠标位置,然后为您mousedownclick节点创建一个 Tween 到该鼠标位置。

    layer.on('mousedown', function() {
        var mousePos = stage.getMousePosition();
        var tween = new Kinetic.Tween({
        node: rect,
        duration: 1,
        x: mousePos.x,
        y: mousePos.y,
        opacity: 1,
        strokeWidth: 6,
        scaleX: 1.5
      }).play();
    
    });
    

    JSFiddle

    注意:要使layer 可点击,我们需要在图层中添加一个大小与舞台宽度和高度相同的透明矩形。Kinetic.Rect在我命名的 jsfiddle 中查看var bg

  2. 将支票放在动画中对您有用吗?

    playerAnim = new Kinetic.Animation(function(frame) {
       var velocity = 50;
       var dist = velocity * (frame.timeDiff / 1000);
       player.move(dist, 0);
       Players.update(dbShape._id, {$set: {x: player.attrs.x, y: player.attrs.y}});
    
       if(player.getX() > 500){
         this.stop();
       }
    }, layer);
    
于 2013-07-19T18:25:34.477 回答