简体   繁体   English

2D游戏,将玩家1转到玩家2

[英]2D game, turn Player 1 to Player 2

I have a 2D game. 我有一个2D游戏。 Each player has its location(x,y) and heading(right is 0deg, up is 90deg etc.) I need a method, to set Player1 heading towards Player2. 每个玩家都有其位置(x,y)和方向(右侧为0度,向上为90度,等等。)我需要一种方法,将Player1的方向设置为朝向Player2。 I tried to calculate it by calculating slope - 我试图通过计算斜率来计算-

slope = (player2.y - player1.y)/(player2.x - player1.x)
heading = degrees(atan(slope))

However it doesn´t return correct result everytime. 但是,它不会每次都返回正确的结果。 Would you recommend me any other approach? 您会推荐我其他方法吗?

You are suffering from the fact that atan(slope) cannot deliver correct values for all directions. 您正遭受atan(slope)无法为所有方向传递正确值的事实。 This is because the slope doesn't include the direction. 这是因为坡度不包含方向。 A turn of 180° will leave the slope unchanged. 旋转180°将使坡度保持不变。 Mathematically, this derives from the fact that -y/-x = y/x. 从数学上讲,这源于-y / -x = y / x的事实。

You are not the first to find this out. 您不是第一个发现此问题的人。 A traditional solution for the situation was always to look closely at the signs of the x and y values and then decide in which quadrant the result of the atan() should be located. 对于这种情况,传统的解决方案是始终仔细查看x和y值的符号,然后确定atan()的结果应位于哪个象限中。

Nowadays this is done in the function with the uninspired name atan2() . 如今,这是在函数中使用非启发性的名称atan2() This receives two values (y and x) and does all that is required to find out the proper direction angle in the range (-180°, +180°], given as radians, so it is the range (-pi, +pi]. 它接收两个值(y和x),并做所有必要的工作以找出适当的方向角(-180°,+ 180°),以弧度表示,因此它是范围(-pi,+ pi ]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM