所以基本上我想做的是,当我在页面的任何地方单击时,火炮的炮管需要旋转以指向鼠标光标,听起来很简单,但我无法使其正常工作,可能是因为我的数学技能不足 :P
目前我拥有的东西类似于这样
/* This is my div with the cannon background image (360 images stitched into one) each "image area" is 100x100px */
obj.cannon = $('#cannon');
/* Get the X/Y of the cannon loc in the dom */
var cannonX = $(obj.cannon).offset().left;
var cannonY = $(obj.cannon).offset().top;
/* Get radians using atan2 */
var radians = Math.atan2(e.pageY-cannonY, e.pageX-cannonX);
/* Convert to degrees */
var degrees = radians * (180/Math.PI);
现在我所处的情况是这样的,因为图像的宽度为100px,我需要将背景位置向右移动100px以使大炮右转一度,因为360个图像* 100px = 总共36000px。 因此,拼接的精灵图像宽度为36000px。
所以
根据图像精灵的当前背景位置插入奇怪的计算,并根据鼠标光标点击的位置应用新的背景位置,然后使用某种setTimeout(animateIt,speed)来“动画”背景位置到新位置。
function animateIt(){
if(newpos!=targetpos) { //Use < > here if we need to add or remove
newpos+=100; //Until we arrive at the new backgroundPosition
$(obj.cannon).css({backgroundPosition: newpos+'px' });
setTimeout(animateIt, speed);
}
}
我现在的想法是对的吗?这应该是一件简单的事情,但我感到很蠢,我的大脑现在好像崩溃了 =P。我的问题是,我不知道如何正确地到达“新的目标背景位置”,然后根据当前的背景位置进行动画 ++ 或 - - 。