在mousemove上旋转对象以面对鼠标指针 [英] Rotating object to face mouse pointer on mousemove

查看:166
本文介绍了在mousemove上旋转对象以面对鼠标指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的游戏中有一个鼠标移动光标,这将使我的物体朝我的鼠标光标射击。我希望我的对象始终旋转以符合我的mousecursor。如何将光标所在的X和Y转换为角度以将我的对象旋转到?



我希望我的小提琴会让事情变得更加清晰我的意思是通过旋转玩家(黑块):的便利功能,当y> 0时它给出了正向角度,当y <0时负角度



atan2返回弧度中的度数,CSS和一起工作,所以我们使用 180 / Math.PI 来在两者之间进行转换。 (弧度是一个角度的度量,当画一个圆的中心角时,它将截取一个长度等于该圆的半径长度的弧。 - 从 here)



最后一条警告 - 由于在浏览器中Y轴是倒置的(意思是说,你进入页面的越远,Y值越高),我们不得不翻转Y轴:我们通过在Y项上添加一个减号:



- (e.pageY - boxCenter [1])



我希望这有助于澄清一些事情......



这是一个孤立的 jsfiddle示例



BTW,你的游戏很难! :)

I've got a mousemove cursor in my game which will make my object shoot towards my mouse cursor. I'd like my object to always rotate along to be in line with my mousecursor. How can i convert the X and Y of where the cursor is to a degree angle to rotate my object to?

I hope my fiddle will make things a little clearer of to what i mean by rotating the player(Black block): http://jsfiddle.net/3nEUv/4/

Here's my mouseMove function now; Only making sure the cursor remains in it's bounding box

function mouseMove(e) {
    if (cursor) {
        if (e.rawX && e.rawY) {
            cursorBoundingBox(e.rawX, e.rawY);
        }
    }
}

解决方案

Basically you need to find the vector between the the point in the center of your box, and the point of the mouse cursor, then calculate the angle and convert it to degrees. Then just apply the angle via CSS:

var box=$(".box");
var boxCenter=[box.offset().left+box.width()/2, box.offset().top+box.height()/2];

var angle = Math.atan2(e.pageX - boxCenter[0], - (e.pageY - boxCenter[1]) )*(180/Math.PI);      

box.css({ "-webkit-transform": 'rotate(' + angle + 'deg)'});    
box.css({ '-moz-transform': 'rotate(' + angle + 'deg)'});

WHAT

Ok, let's take this apart. This is what we have:

The vector AB goes between the center of the box and the mouse position. We went to calculate Θ (theta), which is the angle between the X axis and AB. Since AB creates a triangle with the X and Y axes, we can use the Arctan function to calculate it. More precisely, we use the convenience function of Arctan2 which gives a positive angle when y>0 and negative angle when y<0.

atan2 returns the degrees in radians, and CSS works with degrees, so we convert between the two using 180/Math.PI. (A radian is the measure of an angle that, when drawn a central angle of a circle, intercepts an arc whose length is equal to the length of the radius of the circle. - Taken from here )

One last caveat - Since in the browser the Y axis is inverted (meaning, the further down you go in the page, the higher the Y value gets), we had to flip the Y axis: We did so by adding a minus sign on the Y term:

- (e.pageY - boxCenter[1])

I hope this helps clear some things...

Here's an isolated jsfiddle example

BTW, Your game is hard! :)

这篇关于在mousemove上旋转对象以面对鼠标指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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