- Home /
Proper way to detect both mouse buttons down
Hi,
I'm learning Unity and starting with basic character movement and camera controls. I'm essentially copying WoW character movements. I want to move my game object forward when both mouse buttons are held down. I can make it work but the code seems clumsy and I wonder if there is a better more professional way using Inputs or "something". My code is below:
bool _running = false;
bool _leftDown = false;
bool _rightDown = false;
public virtual void GetInput()
{
//forwardInput = Input.GetAxis(inputSettings.FORWARD_AXIS); // interpolated
if (Input.GetMouseButtonDown(0))
{
_leftDown = true;
}
if (Input.GetMouseButtonDown(1))
{
_rightDown = true;
}
if (_leftDown && _rightDown)
{
_running = true;
}
if (Input.GetMouseButtonUp(0))
{
_leftDown = false;
_running = false;
}
if (Input.GetMouseButtonUp(1))
{
_rightDown = false;
_running = false;
}
turnInput = Input.GetAxis(inputSettings.TURN_AXIS);
jumpInput = Input.GetAxisRaw(inputSettings.JUMP_AXIS);
}
I call this in Update and follow on from this in FixedUpdate to actually use the _running flag to setup forward velocity etc. I guess Im asking if there is a one liner for all of this. Seems like a lot of code for something so simple.
I tried creating a custom input with Mouse 0 + Mouse 1 but the editor wouldn't allow it.
Thanks
Answer by hexagonius · Oct 27, 2016 at 09:18 PM
You can just do this and it's the same:
bool _running = false;
bool _leftDown = false;
bool _rightDown = false;
public virtual void GetInput()
{
//forwardInput = Input.GetAxis(inputSettings.FORWARD_AXIS); // interpolated
_running = Input.GetMouseButton(0) && Input.GetMouseButton(1);
turnInput = Input.GetAxis(inputSettings.TURN_AXIS);
jumpInput = Input.GetAxisRaw(inputSettings.JUMP_AXIS);
}
Ah brilliant thanks. I originally tried using mouse down
_running = Input.Get$$anonymous$$ouseButtonDown(0) && Input.Get$$anonymous$$ouseButtonDown(1);
I spoke with someone today and they said it's because it Get$$anonymous$$ouseButtonDown is only triggered in a single frame.
Your answer
Follow this Question
Related Questions
Mouse Flight Doesn't Allow for Rolling 1 Answer
Android based ARCore example ObjectManipulation using Joystick Controller 0 Answers
Convert current rigidbody velocity to transform.forward 0 Answers
[2d] Player sometimes doesn't jump up while moving and jumping at the same time 1 Answer
How to code a burst of speed? 1 Answer