C# 向Unity2D中二维对象的旋转添加夹点

C# 向Unity2D中二维对象的旋转添加夹点,c#,unity3d,C#,Unity3d,我已经工作了很长时间,试图在Unity2D中的2D对象上实现一个夹具。我已经为这个问题挣扎了好几个星期了。我有一个自行向上移动的火箭飞船,我正试图使它旋转不超过40度。需要注意的一些细节是,飞船旋转(当然是x轴)并向鼠标移动(x轴,不会比当前速度更高),以避免即将到来的障碍物。这是我的飞船代码: public class MiniGameRocketShipController : MonoBehaviour { public Vector2 velocity = new Vector2

我已经工作了很长时间,试图在Unity2D中的2D对象上实现一个夹具。我已经为这个问题挣扎了好几个星期了。我有一个自行向上移动的火箭飞船,我正试图使它旋转不超过40度。需要注意的一些细节是,飞船旋转(当然是x轴)并向鼠标移动(x轴,不会比当前速度更高),以避免即将到来的障碍物。这是我的飞船代码:

public class MiniGameRocketShipController : MonoBehaviour
{
    public Vector2 velocity = new Vector2(0f, 1500f);

    private Vector2 directionX;
    private Vector2 directionY;

    public Rigidbody2D rb;

    public new Camera camera;

    public float moveSpeed = 100f;
    public float rotation;

    private void Start()
    {
        rotation = rb.rotation;
    }

    private void Update()
    {
        rb.AddForce(velocity * Time.deltaTime);
        rb.velocity = new Vector2(directionX.x * moveSpeed, directionY.y * moveSpeed);

        FaceMouse();
    }

    void FaceMouse()
    {
        if (rotation > 180)
        {
            rotation = 360;
        }

        rotation = Mathf.Clamp(rotation, -40f, 40f);
        rb.rotation = rotation;

        Vector3 mousePosition = Input.mousePosition;
        mousePosition = camera.ScreenToWorldPoint(mousePosition);

        directionX = (mousePosition - transform.position).normalized;
        directionY = transform.position.normalized;

        transform.up = directionX;
    }
}

可以使用
Vector2.SignedAngle
Mathf.Clamp
执行此操作。评论中的解释:

// world direction to clamp to as the origin
Vector2 clampOriginDirection = Vector2.up;

// what local direction should we compare to the clamp origin
Vector2 clampLocalDirection = Vector2.up;

// how far can the local direction stray from the origin
float maxAbsoluteDeltaDegrees = 40f;

void ClampDirection2D()
{ 
    // world direction of the clamped local
    // could be `... = transform.up;` if you are ok hardcoding comparing local up 
    Vector2 currentWorldDirection = transform.TransformDirection(clampLocalDirection);

    // how far is it from the origin?
    float curSignedAngle = Vector2.SignedAngle(clampOriginDirection, currentWorldDirection);

    // clamp that angular distance
    float targetSignedAngle = Mathf.Clamp(curSignedAngle, -maxAbsoluteDeltaDegrees,
            maxAbsoluteDeltaDegrees);

    // How far is that from the current signed angle?
    float targetDelta = targetSignedAngle - curSignedAngle;

    // apply that delta to the rigidbody's rotation:
    rb.rotation += targetDelta;
}


这对我没用。在哪里调用函数?它是更新还是开始?@Concepts我会在
Update
的末尾称之为。不过,只要定义了
rb
,它就可以在任何需要它的地方工作。在绘制帧之前,您只需确保不会覆盖其对rb.rotation所做的任何更改,除非您真的打算这样做。好的,我马上试试这个。您使用的是刚体2D还是3D?这是一个2D游戏。另外,您是否需要更改clampOriginDirection和clampLocalDirection?只是想知道。到目前为止,我的代码还不起作用。您在问题中输入的代码定义了
public rigiidbody2d rb,这就是我在这个答案中写的。你说你想把局部的
向上
钳制到全局的
向上
的30度以内,所以我会把
钳制方向
钳制方向
改为
向量2.up
,因为它们在这里。我还没有设法让它起作用。谢谢你的努力。我真的很感激。