[英]JS - push ball at an angle
I want to push a ball at an angle using the mouse. 我想用鼠标以一定角度推球。
To do this, so far I have: 为此,到目前为止,我有:
But the ball isn't moving when I hit the ball. 但是当我击球时,球没有动。 It seems to trail behind. 似乎落后了。
And sometimes it goes off on weird angles. 有时它会以怪异的角度消失。
Lastly, sometimes the angle gives NaN. 最后,有时角度为NaN。 Not sure why it's not a number 不确定为什么不是数字
Any thoughts? 有什么想法吗?
FIDDLE : http://jsfiddle.net/edH59/ 字段 : http : //jsfiddle.net/edH59/
Code: 码:
//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;
}
To have an angle, you have to store the previous location of the mouse and consider the current angle as the angle between last measure and current. 要确定角度,必须存储鼠标的先前位置,并将当前角度视为最后一个小节与当前角度之间的角度。 You could do some kind of averageing on this to smooth the result. 您可以对此进行某种平均以使结果平滑。 In my demo the current direction is drawn in red if the direction vector is long enough. 在我的演示中,如果方向矢量足够长,则当前方向以红色绘制。
The computation of the angle is done with a classical atan2. 角度的计算是通过经典的atan2完成的。
var mouseAngle = Math.atan2(my-lastmy, mx-lastmx);
You can have a look at the result here : http://jsfiddle.net/gamealchemist/z3U8g/4/embedded/result/ 您可以在这里查看结果: http : //jsfiddle.net/gamealchemist/z3U8g/4/embedded/result/
code is here : http://jsfiddle.net/gamealchemist/z3U8g/4/ 代码在这里: http : //jsfiddle.net/gamealchemist/z3U8g/4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.