【问题标题】:Moving a vector "straight out" along a fixed angle沿固定角度“直接”移动矢量
【发布时间】:2013-04-05 04:32:27
【问题描述】:

我已经搜索了这个问题的答案并尝试了许多建议的解决方案,但似乎没有一个可行。我一直在为此苦苦挣扎,因此非常感谢任何见解。

我在 JS 画布上有 3 个形状(我想是矢量),每个形状的方向表示为偏离 0 的度数和宽度。我需要从它的方向“直接”拖动这些形状之一。这很难用语言解释,所以请查看我创建的图形:

中间(对角线)形状为 45 度。它的原点是红点,(x1,y1)。用户拖动形状,他们的鼠标位于绿点 (x2,y2)。由于形状的原点在左下方,我需要将形状定位在浅蓝色形状的位置,就好像用户从形状的原点直接向外拖动一样。

我认为这并不重要,但我用来执行此操作的库是 KineticJS。这是我可用的代码和一些信息,它们可能有助于解决问题。此代码将形状定位在鼠标顶部,这不是我想要的:

var rotationDeg = this.model.get("DisplayOri"), // rotation in degrees
    rotationRadians = rotationDeg * Math.PI / 180, // rotation in rads
    unchanged = this.content.getAbsolutePosition(),  // {x,y} of the shape before any dragging

    dragBoundFunc = function (changed) {
        // called on a mouseMove event, so changed is always different and is the x,y of mouse on stage
        var delta = {
            x: changed.x - unchanged.x,
            y: changed.y - unchanged.y
        };

        return changed; // go to the mouse position
    };

[edit] 我应该提一下,“return delta”的明显效果是行不通的。

【问题讨论】:

    标签: javascript vector html5-canvas kineticjs trigonometry


    【解决方案1】:

    听起来你想限制对象的移动。

    1. 确定代表约束轴的向量:也就是说,我们只希望运动沿着这条线发生。从您的绘图中可以看出,这是从红点到左侧的短线方向。该向量的方向为-1/m,其中m 是我们移动的直线的斜率。

    2. 限制运动。移动由鼠标移动增量表示 - 但我们只想要该移动在约束轴方向上的部分。这是通过两个向量的dot product 完成的。

    所以在伪代码中

     m = (line.y2 - line.y1)/(line.x2 - line.x1)
     constraintSlope = -1/m
    
     contraintVector = {1, constraintSlope}  //unit vector in that direction
     userMove = {x2-x1, y2-y1}               //vector of mouse move direction
    
     projection = userMove.x * constraintVector.x + userMove.y * constraintVector.y
    
     translation = projection * constraintVector   //scaled vector
    

    【讨论】:

    • +1 @Mikeb:很好的解决方案!它非常适合 OP 的需求,因为 KineticJS 允许自定义的 dragBoundFunc 来适应您的约束解决方案。
    • 我可以看到这是我需要的,但我不确定如何获得你所说的行的 x2,y2。该线的 x2,y2 是蓝色形状需要捕捉到的最终端点......换句话说,line.x2,line.y2 是我试图在原始问题中找到的同一点是'是吗?
    • 您要移动的线有两个端点 - 红点在其中一个附近/上方,另一个是深蓝色(未移动)线的另一端。
    • 哦 - 我误会了。我认为“线”是将红色原点连接到目的地 x,y 的线段。谢谢!
    • 抱歉,我花了这么长时间才将其标记为答案 - 我已经转向其他事情了!
    猜你喜欢
    • 2012-12-27
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    相关资源
    最近更新 更多