How can I move the mouse position whilst key is pressed?
I'm using Unity 5.5.2 and even if I create a new Unity project, in the editor, if I hold down a key (any key), then my mouse position locks and I cannot move it.
I want my player to move towards my mouse position (no click) and I also want to be able to hold down a key (e.g. space bar) to continuously fire. When my key is held down, the mouse does not move. Try it, just create a new Unity project, hit run and hold down a key, mouse is locked!
How can I change that?
Answer by avazutaev · Mar 30, 2017 at 10:09 PM
If your space is in 2D (in 3D need some changes for this code) this should work:
private Vector3 moveDirection;
in Update function:
Vector3 currentPosition = transform.position;
if( Input.GetButton("Fire1") ) {
Vector3 moveToward = Camera.main.ScreenToWorldPoint( Input.mousePosition );
moveDirection = moveToward - currentPosition;
moveDirection.z = 0;
moveDirection.Normalize();
}
Vector3 target = moveDirection * moveSpeed + currentPosition;
transform.position = Vector3.Lerp( currentPosition, target, Time.deltaTime );
P.S. If you want to run after mouse position without pushing it, just remove "if" statement
Thanks, this actually would work as my Fire1 is by default mouse click 1. I actually could do that. But imagine that I want to hold down Jump (Space bar on my keyboard) to fly up or something whilst at the same time moving my mouse to move the player. In this scenario, when I hold down the space bar then Input.mousePosition does not update as the actual cursor on my screen does not move
you can use this script to move and put jump animation and play it by pushing the space button, or you can work in 3d than your moving script doesn't interrupt your jumping script.
Your answer
Follow this Question
Related Questions
Bullet to Mouse Position? 1 Answer
Projectile not firing from mouse location 1 Answer
Can't get a gameObject to follow my mouse 0 Answers
Raycast not drawing where i tell it 1 Answer
Shoot towards mouse with offset 0 Answers