我想用鼠标以一定角度推球。
要做到这一点,到目前为止,我有:
但是当我击球时球没有移动。它似乎落后了。
有时它会在奇怪的角度出现。
最后,有时角度会给出NaN。不确定为什么它不是数字
有什么想法?
FIDDLE :http://jsfiddle.net/edH59/
代码:
//Get angle of mouse movement
function getAngle (x1, y1, x2, y2) {
var dY = Math.abs(y2-y1); //opposite
var dX = Math.abs(x2-x1); //adjacent
var dist = Math.sqrt((dY*dY)+(dX*dX)); //hypotenuse
var sin = dY/dist; //opposite over hypotenuse
var radians = Math.asin(sin);
var degrees = radians*(180/Math.PI); //convert from radians to degrees
angle = degrees;
return degrees; //return angle in degrees
}
$("canvas").mousemove(function(e) {
getDirection(e);
if (!set) {
x1 = e.pageX,
y1 = e.pageY,
set = true;
}
clearTimeout(thread);
thread = setTimeout(callback.bind(this, e), 100);
});
$(".anotherBox").mouseenter(function(e) {
pos = $(this).position();
box2X = pos.left;
box2Y = pos.top;
if(animate) {
$(this).animate({
top : newY+"px",
left: newX+"px",
}, "slow");
}
animate = false;
});
}
function calcNewLoc (x, y, xDist, yDist) {
newX = x + (xDist * Math.cos(angle));
newY = y + (yDist * Math.sin(angle));
}
function callback(e) {
x2 = e.pageX;
y2 = e.pageY;
t2 = new Date().getTime();
var xDist = x2 - x1,
yDist = y2 - y1,
time = t2 - t1;
//to calc angle... need to get starting position and ending position
$(".angle").html(getAngle(x1, y1, x2, y2));
calcNewLoc(x1, y1, xDist, yDist);
animate = true; //only allow animation of ball once new locations are calculated
log("mouse has stopped");
set = false;
}
答案 0 :(得分:0)
要获得角度,您必须存储鼠标的先前位置,并将当前角度视为上次测量和当前角度之间的角度。您可以对此进行某种平均以平滑结果。在我的演示中,如果方向向量足够长,则当前方向以红色绘制。
角度的计算是用经典的atan2完成的。
var mouseAngle = Math.atan2(my-lastmy, mx-lastmx);
您可以在此处查看结果: http://jsfiddle.net/gamealchemist/z3U8g/4/embedded/result/