且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据角色周围的旋转动画

更新时间:2023-11-19 12:55:34

所以我下面要做的基本上是计算光标和播放器之间的角度,然后相应地设置动画. 如果您有疑问或需要澄清,只需答复即可,但是即使将代码简单地放在Update函数中,我也认为代码可能会起作用.在这种情况下,Input.mousePosition可能不适用于2D,只需使用Camera.main.ScreenToWorldPoint(Input.mousePosition)进行切换即可.祝你好运!

So what I basically did below is calculate angle between cursor and player then set the animations accordingly. if you have questions or need clarification just reply but I feel like the code might work even if you simply put it in your Update function. Input.mousePosition may not readily work for 2D in that case you can just switch it up with Camera.main.ScreenToWorldPoint(Input.mousePosition). Good luck!

//direction towards cursor
Vector2 towardCursor = Input.mousePosition - transform.position;


//angle between worldspace right and direction towards cursor
//signedAngle to detect negative angles
float angleVertical = Vector2.SignedAngle(Transform.right, towardCursor);

//angle between worldspace up and direction towards cursor
float angleHorizontal = Vector2.SignedAngle(Transform.up, towardCursor);

//reversed to make clockwise angles negative angles        
angleVertical = -angleVertical;
angleHorizontal = -angleHorizontal;

if (angleVertical > 90
||
angleVertical < -90)
{

angleVertical = angleVertical > 0 ? 180 - angleVertical : -180 - angleVertical;

}

if (angleHorizontal > 90
||
angleHorizontal < -90)
{

angleHorizontal = angleHorizontal > 0 ? 180 - angleHorizontal : -180 - angleHorizontal;

}

animator.setFloat("Vertical", angleVertical / 90);
animator.setFloat("Horizontal", angleHorizontal / 90);