moshe ralf moshe ralf - 1 month ago 19
C# Question

How to switch between one click mouse and mouse hold down?

When it's one click i want the character to Walk to the mouse position.
But if it's holding down the mouse button i want it to rotate the character.
But for some reason it's all the time on the Idle state. So when i make one click the character jump in small jump and not walking to the mouse position.

If i will remove the whole part of the if (Input.GetMouseButton(0)) then when clicking the mouse it will walk fine to the mouse position but once added this part he will not walk.

void Update()
if (Input.GetKeyDown(KeyCode.Mouse0))
_animator.CrossFade("Walk", 0);
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitdist = 0.0f;

if (playerPlane.Raycast(ray, out hitdist))
Vector3 targetPoint = ray.GetPoint(hitdist);
targetPosition = ray.GetPoint(hitdist);
targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
destination = targetPosition;

if (Input.GetMouseButton(0))
_animator.CrossFade("Idle", 0);
RaycastHit hit;
Ray ray1 = Camera.main.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray1, out hit) && != "ThirdPersonController")
transform.LookAt(ray1.GetPoint(100)); //the number here is compltely arbitrary

apk apk

Input.GetMouseButton(int) returns true always if the mouse button is being pressed. Input.GetMouseButtonDown(int) returns true only on the first frame during which the mouse button is clicked.

So given your code, the possibilities are:

  • No button is being pressed. None of the if blocks are entered.
  • This is the exact frame when the mouse button was clicked. Both of the if blocks are executed. Your animator state is set to Walk and then immediately to Idle and your character doesn't move.
  • The mouse button was pressed down a few frames ago and is still being held down. Only the second if block is executed. Your animator state is set to Idle and the character doesn't move.

If you have decided to use this particular control scheme, you should consider implementing some sort of delay - maybe mouse button presses shorter than 0.2s should count as a click and presses longer than 0.2s should count as a hold. This way your predicates won't overlap.