d3过渡中圆的碰撞/重叠检测 [英] Collision/overlap detection of circles in a d3 transition

查看:136
本文介绍了d3过渡中圆的碰撞/重叠检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用d3为地图上的路径(路径)设置动画。当路线到达路线上的某个点时,我想弹出一些信息。

I'm using d3 to animate a route (path) on a map. When the route reaches a point along the route I'd like to popup some information.

我的大部分代码都基于以下示例。 http://bl.ocks.org/mbostock/1705868 。我真的只是想确定是否有一种方法来检测过渡圆在这个例子中何时碰撞或重叠任何静止圆圈。

Most of my code is based on the following example. http://bl.ocks.org/mbostock/1705868. I'm really just trying to determine if there is a way to detect when the transitioning circle collides or overlaps any of the stationary circles in this example.

推荐答案

您可以检测碰撞<你的补间函数中的/ a>。定义一个从补间函数内部调用的碰撞函数,如下所示:

You can detect collision in your tween function. Define a collide function to be called from inside the tween function as follows:

function collide(node){
    var trans = d3.transform(d3.select(node).attr("transform")).translate,
      x1 = trans[0],
      x2 = trans[0] + (+d3.select(node).attr("r")),
      y1 = trans[1],
      y2 = trans[1] + (+d3.select(node).attr("r"));

  var colliding = false;
  points.each(function(d,i){
    var ntrans = d3.transform(d3.select(this).attr("transform")).translate,
      nx1 = ntrans[0],
      nx2 = ntrans[0] + (+d3.select(this).attr("r")),
      ny1 = ntrans[1],
      ny2 = ntrans[1] + (+d3.select(this).attr("r"));


      if(!(x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1))
        colliding=true;
  })

  return colliding;
}

其中积分是静止点和节点是转换元素。什么碰撞确实检查节点 是否与任何点重叠(如图所示) 此处的碰撞检测示例)。

Where points are the stationary points, and node is the transitioning element. What collide does is check whether node overlaps with any of the points (as shown in collision detection example here).

因为我们需要<要传递给补间函数的code> node ,我们用补间中的替换在Mike示例中使用的 attrTween

Because we need the node to be passed to the tween function, we replace attrTween used in Mike's example, with tween:

circle.transition()
      .duration(10000)
      .tween("attr", translateAlong(path.node()))
      .each("end", transition);

最后,调用我们的碰撞的补间函数

function translateAlong(path) {
  var l = path.getTotalLength();
  return function(d, i, a) {
    return function(t) {
      var p = path.getPointAtLength(t * l);

      d3.select(this).attr("transform","translate(" + p.x + "," + p.y + ")");

      if(collide(this))
        d3.select(this).style("fill", "red")
       else
        d3.select(this).style("fill", "steelblue")
    };
  };
}

参见这里的完整演示

这篇关于d3过渡中圆的碰撞/重叠检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆