用鼠标拖动矢量点 [英] Dragging point along vector with mouse

查看:143
本文介绍了用鼠标拖动矢量点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去几天我一直在尝试三角法,并且想出了一些游戏中找到的那些整齐的五边形。 ( 小提琴!

I've been experimenting with trigonometry for the past few days, and came up with one of those neat stat pentagons you find in some games. (fiddle!)

我真的想允许内部多边形的顶点可拖动以更改stat值。我的鼠标功能运行良好,但用鼠标拖动点在线上的最好方法是什么?

I'd really like to allow the vertices of the inner polygon to be draggable to change the stat values. I have mouse functionality working well, but what's the best way to drag a point on the line with the mouse?

图片可视化我的问题;红色多边形是当前多边形,粉红色线表示新的多边形,粉红色圆形突出显示顶点的新点,蓝色线是矢量切线,绿色圆圈是光标。 strong>

I've created a picture to visualize my problem; the red polygon is the "current" polygon, the pink lines represent the new polygon, the pink circle emphasizes the new point for the vertex, the blue line is the vector tangent, and the green circle is the cursor.

我写了一个程序来处理向量,但我不知道如何将它应用到这种情况。

I've written a program which deals with vectors before, but I'm not sure how to apply it to this situation.

这里是一些代码(在循环函数中):

Here's some code (in the loop function):

for(var i = 0; i < innerPolygonKnobs.length; i ++){
    var knob = innerPolygonKnobs[i];
    distX = knob.x-mouse.x;
    distY = knob.y-mouse.y;
    distTotal = Math.sqrt(distX*distX + distY*distY);
    if(distTotal < 8){
        if(!knob.over)change = true;
        knob.over = true;
        if(mouse.down){
            // What goes here?
        }
    } else {
        if(knob.over)change = true;
        knob.over = false;
    }
}
if(change)redraw();

非常感谢! :D

推荐答案

这个函数将给你在任何给定行上最接近鼠标的点:

This function will give you the closest point to the mouse on any given line:

// given a line defined like this
var line={x0:50,y0:50,x1:150,y1:150};

// calculate the closest point on the line to [x,y]
function getClosestPointOnLine(line,x,y) {
    //
    lerp=function(a,b,x){ return(a+x*(b-a)); };
    var dx=line.x1-line.x0;
    var dy=line.y1-line.y0;
    var t=((x-line.x0)*dx+(y-line.y0)*dy)/(dx*dx+dy*dy);
    t=Math.min(1,Math.max(0,t));
    var lineX=lerp(line.x0, line.x1, t);
    var lineY=lerp(line.y0, line.y1, t);
    return({x:lineX,y:lineY});
};

然后重新绘制内部多边形以连接到上述点。

Then just redraw your inner polygon to connect to the point found above.

有趣的应用程式...祝你好运!

Interesting app...good luck with it!

这篇关于用鼠标拖动矢量点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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