Home > Net >  Rewriting my look at mouse position using a controller analog stick
Rewriting my look at mouse position using a controller analog stick

Time:02-28

I'm currently rewriting my code to use the new Unity Input system. Previously, I had the below code to orientate my "fire point" towards the mouse:

    Vector2 mousePosition = cam.ScreenToWorldPoint(Input.mousePosition);
    Vector2 lookDir = mousePosition - rb.position;
    float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
    rb.rotation = angle;

I need to do this now with the controller right stick instead but I'm not sure how to do it. I have this on the event callback:

public void OnAim(InputAction.CallbackContext context)
{
    aimDir = context.ReadValue<Vector2>();
}

I tried swapping out mousePosition for aimDir in the original code block but that didn't work. Any suggestions?

CodePudding user response:

Your current method is taking the coordinates of the mouse on the screen, and transforming it to world space, then calculating your look direction based off this.

This will obviously not work for your controller because it's stick position has nothing to do with the mouse on the screen.

So lets look at an alternative.

You could have some variable keeping track of the direction you are currently facing, but it looks like your rigidbody can already be doing this with it's transform.forward.

You can then take your stick input and use this to create a delta to rotate your rigidbody by, scaling it by some speed factor and using Time.(Fixed)DeltaTime of course.

  • Related