如何计算对角线速度?
我正在编写一个游戏来练习一些编程,我遇到了这个问题。在我的游戏中,屏幕上有圆圈。当用户点击屏幕时,圆圈应该远离点击。我得到了按下鼠标按钮的点的 x 和 y 位置,并且得到了每个 cicle 对象的 x 和 y 位置。
我用下面的代码找到了圆的中心
float cx = circle.getX()+circle.getRadius();
float cy = circle.getY()+circle.getRadius();
并找到了从圆的边缘到鼠标单击的距离我这样做了
float distance = (float) Math.sqrt( ((cx-x)*(cx-x)) + ((cy-y)*(cy-y)) ) - circle.getRadius();
现在在检查圆是否足够接近单击之后,我怎样才能分割速度1f,例如圆的变量vx和vy?
编辑:实际上我想要加速,但我想都是一样的。
I'm writing a game of sorts to practice some programming, and i've come across this problem. In my game, there are circles on the screen. And when the user clicks on the screen, the circles should move away from the click. I've got the x and y position of the point where the mouse button was pressed, and i have the x and y position of each cicle object.
I found the center of the circles with the following code
float cx = circle.getX()+circle.getRadius();
float cy = circle.getY()+circle.getRadius();
And to find the distance from the edge of the circle to the mouse click I did this
float distance = (float) Math.sqrt( ((cx-x)*(cx-x)) + ((cy-y)*(cy-y)) ) - circle.getRadius();
Now after I check if the circle is close enough to the click, how can I split a velocity of 1f, for example, to the circle's variables vx and vy?
EDIT: Well actually I wanted acceleration, but I guess it's all the same.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这听起来像是
java.lang.Math
中的sin
和cos
的工作:http://download.oracle.com/javase/6/docs/api/java/lang/Math.html< /a> .一旦您知道了总速度(上面示例中的
1f
)和角度(以弧度为单位),速度的水平分量就是v * cos(angle)
,并且垂直分量是v * sin(angle)
。如果您想将其移开,您可能需要取消该角度。
要根据水平和垂直距离计算角度,请使用
atan2
。顺便说一句,如果您不想取不必要的平方根,并且想避免像三角函数那样计算级数的成本,请查看 http://www.youtube.com/user/njwildberger#p/u/368/9wd0i44vK04 。
This sounds like a job for
sin
andcos
injava.lang.Math
: http://download.oracle.com/javase/6/docs/api/java/lang/Math.html .Once you know the total velocity (
1f
in your example above) and the angle (in radians), the horizontal component of the velocity isv * cos(angle)
, and the vertical component isv * sin(angle)
.You probably need to negate the angle if you want to move it away.
To calculate an angle from horizontal and vertical distances, use
atan2
.Btw, if you don't want to take unnecessary square roots, and want to avoid the cost of computing series the way trigenometric functions do, take a look at http://www.youtube.com/user/njwildberger#p/u/368/9wd0i44vK04 .
找到从鼠标到圆心的线,这应该是“力”矢量。这个向量将为您提供方向,现在您只需要弄清楚距离如何影响幅度。
Find the line from the mouse to the center of the circle and that should be the "force" vector. This vector will give you the direction, now you just need to figure out how distance affects the magnitude.
您可以首先按照迈克的建议找到角度并使用 cos 和 sin 函数。
或者使用:
You could first find angle as Mike suggested and use cos and sin functions.
Or use: