Search code examples
unity-game-engine2dquaternions

Make an object rotate according to mouse movement. [UNITY C#]


I’m starting a learning project. The idea is that you have an archer character that is static, that has a bow attached to it that shoots arrows to targets of varying difficulty. Turns out that right at the start I’m stuck. How do I make it so that the bow rotates when the player clicks and holds the mouse anywhere on the screen? So I click+hold and move left/right and the bow rotates left/right to aim the shot. I’d like to also eventually make it portable to phones (so you’d tap+hold etc).


Solution

  • Stack Overflow isnt a code writing service but i will explain what you must do:

    Method 1 (Exact Aiming):

    For every frame the mouse is down:

    1. Make a Ray from a screen point... hint (use camera.ScreenPointToRay).
    2. Get a far point along the Ray using ray.GetPoint(distance);.
    3. Bow.Transform.LookAt(newPoint, Vector3.Up);.

    Method 2 (Continuous Movement):

    1. Make a variable oldMousePos to store a Vector2 location.
    2. Record your initial screen click position into that variable on a mouse down event.
    3. Have a function that runs once every frame the mouse stays down.
    4. For the direction of the rotation of the bow, you can use (newMousePos - oldMousePos).normalized;.
    5. For the speed of rotation for your bow, you can use (newMousePos - oldMousePos).sqrMagnitude;.