Добавление зажима для поворота 2D-объекта в Unity2D - PullRequest
0 голосов
/ 03 марта 2020

Я давно работаю, пытаясь реализовать зажим на моем 2D-объекте в Unity2D. Я боролся с этой проблемой уже несколько недель. У меня есть ракетный корабль, который движется вверх самостоятельно, и я пытаюсь сделать его там, где вы не можете go вращаться дальше 40 градусов. Некоторые детали, на которые следует обратить внимание, это то, что корабль вращается (ось X, конечно) и движется к мышке (ось X, не на 1004 * больше, чем текущая скорость), чтобы избежать препятствий, которые скоро появятся. , Вот мой код для корабля:

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;
    }
}

1 Ответ

0 голосов
/ 03 марта 2020

Вы можете использовать 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;
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...