You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中Sprite朝向鼠标位置旋转角度异常问题求助

解决Sprite朝向鼠标旋转角度异常问题

核心问题出在Sprite初始朝向和Mathf.Atan2的角度基准不匹配:

  • Mathf.Atan2(direction.y, direction.x)计算的是从**x轴正方向(向右)**为0度的旋转角度
  • 绝大多数Sprite默认是朝上(y轴正方向),两者差了90度,直接用计算出的角度会导致旋转错位

修正方案

  1. 调整角度偏移量,对齐Sprite初始朝向
    把计算出的角度减去90度(适配Sprite默认朝上的情况),让旋转基准和Sprite的初始方向匹配。
  2. 优化重复代码,避免冗余计算

修改后的完整代码:

public void Look(InputAction.CallbackContext context)
{
    if (context.performed)
    {
        _mousePosition = context.ReadValue<Vector2>();
    }
}

// 抽取公共方法,避免重复计算鼠标方向
private Vector2 GetMouseDirection()
{
    Vector3 worldMousePosition = _mainCamera.ScreenToWorldPoint(_mousePosition);
    worldMousePosition.z = 0;
    return (worldMousePosition - transform.position).normalized;
}

private void RotateToMouse()
{
    Vector2 direction = GetMouseDirection();
    // 减去90度,对齐Sprite默认朝上的初始方向
    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90f;
    transform.rotation = Quaternion.Euler(0, 0, angle);
}

private void UpdateAnimation()
{
    Vector2 direction = GetMouseDirection();
    // 这里改为用鼠标方向控制动画(原代码误用了_moveInput,若需移动方向可改回)
    _animator.SetFloat("InputX", direction.x);
    _animator.SetFloat("InputY", direction.y);
}

额外注意事项

  • 如果你的Sprite初始朝向不是朝上(比如朝下/左/右),需要调整偏移值:比如默认朝下就加90度,默认朝左就加180度
  • 可以先打印angle的值,观察鼠标在不同位置时的角度变化,再微调偏移量确保完全匹配
  • 原UpdateAnimation方法里误用了_moveInput,如果是做瞄准相关动画,应该用鼠标方向参数;如果是移动动画,再改回_moveInput

内容的提问来源于stack exchange,提问作者Craig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 06:02:42