- Home /
How do I get the Vector2 from an input action in code? (New Input System)
I'm trying to make a dash ability that dashes in the direction of the mouse or in the direction that the controller knob is being held. I set up the input, and set the action type to value with control type as Vector2, I also set up the logic for how my dash will work. The logic should work fine, but I don't actually know how to get the Vector2 from the input to use in the dash. Here's the code, if you can help me that would be awesome. Thanks!
public void Dash(InputAction.CallbackContext context)
{
//dash when dash button is pressed
if (context.performed && canDash == true)
{
//stuff here to actually dash
canDash = false;
StartCoroutine(DashTime());
}
}
public void DashAim(???)
{
//get vector2 from input (if that's how it works)
}
IEnumerator DashTime()
{
yield return new WaitForSeconds(3f);
canDash = true;
}
}
I still need help with this, if anyone can help me please check this out
Answer by andrew-lukasik · Aug 29, 2021 at 09:33 PM
public void DashAim ( InputAction.CallbackContext ctx )
{
Vector2 vec = ctx.ReadValue<Vector2>();
}
Longer answer:
public class DasherThing : MonoBehaviour
{
Controls _controls;
float _lastDashTime = float.MinValue;
float _dashDelay = 3f;
public bool CanDash => Time.time > _lastDashTime+_dashDelay;
void Awake ()
{
_controls = new Controls();
_controls.player.Enable();
_controls.player.dash.performed += Dash;
}
void OnDestroy ()
{
_controls.Dispose();
}
public void Dash ( InputAction.CallbackContext ctx )
{
// dash when dash button is pressed
if( CanDash==true )
{
// update dash time:
_lastDashTime = Time.time;
// read inputs:
Vector2 aim = _controls.player.aim.ReadValue<Vector2>();
// execute a dash:
}
else Debug.Log("dash is not ready, communicate that with sound here");
}
}
Controls
is a placeholder name for c# class name generated from your input action assets
Thank you, now I know how to get the input. Do you know how to reference that input in another void, now that I have it?
Read it straight from the input system there:
Vector2 aim = _controls.player.aim.ReadValue<Vector2>();
Also, you're organizing your code for this in the wrong/messy way (coroutine is not needed). I expanded my original answer with a rough example.
hmm, I tried to do it more like your example, but for some reason the "Controls _controls;" at the beginning immediately creates an error. it says "The type or namespace name 'Controls' could not be found (are you missing a using directive or an assembly reference?)" I have "using UnityEngine.InputSystem;". Do I need something else as well?
Your answer
Follow this Question
Related Questions
dash towards mouse position? (New Input System) 2 Answers
Need Help with MousePos and dashing 0 Answers
Input.mouseposition is confused by multiple clicks 1 Answer
How do I use controller knob input like mouse position? (New Input System) 1 Answer
How to get input from wheel(car direction) joystick? 1 Answer