Daniel Halfoni
Daniel Halfoni

Reputation: 507

How can i make the player idle when not moving the mouse?

When i'm moving the mouse around the player is walking facing to the mouse cursor. Now i want to make that if i'm not moving the mouse to make the player idle.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WorldInteraction : MonoBehaviour
{
    public int speed = 5; // Determines how quickly object moves towards position
    public float rotationSpeed = 5f;
    private Animator _animator;
    private bool toMove = true;
    private Vector3 tmpMousePosition;

    UnityEngine.AI.NavMeshAgent playerAgent;

    private void Start()
    {
        tmpMousePosition = Input.mousePosition;
        _animator = GetComponent<Animator>();
        _animator.CrossFade("Idle", 0);

        playerAgent = GetComponent<UnityEngine.AI.NavMeshAgent>();
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0) && toMove == false &&
  !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) 
       {
            toMove = true;
        }
        if (Input.GetMouseButtonDown(1) && toMove == true)
        {
            toMove = false;
        }
        if (toMove == true)
        {
            GetInteraction();
        }
    }

    void GetInteraction()
    {

        if (tmpMousePosition != Input.mousePosition)
        {
            tmpMousePosition = Input.mousePosition;
            _animator.CrossFade("Walk", 0);
            Ray interactionRay = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit interactionInfo;
            if (Physics.Raycast(interactionRay, out interactionInfo, Mathf.Infinity))
            {
                GameObject interactedObject = interactionInfo.collider.gameObject;
                if (interactedObject.tag == "Interactable Object")
                {
                    interactedObject.GetComponent<Interactable>().MoveToInteraction(playerAgent);
                }
                else
                {
                    playerAgent.destination = interactionInfo.point;
                }
            }
        }
        else
        {
            _animator.CrossFade("Idle", 0);
        }
    }
}

I'm using the variable tmpMousePosition to check if the mouse is in a move or not. The problem is when it's on a move and the player is in "Walk" mode the player is stuttering each a second or so.

The idea is when the mouse is moving then move the player when the mouse is not moving make the player in Idle.

In the Update function i'm using a bool to stop/continue the interaction like a switch with the mouse left/right buttons. But now i want to use the mouse movement to Walk/Idle the player.

Upvotes: 0

Views: 371

Answers (1)

Cristiano Soleti
Cristiano Soleti

Reputation: 858

Just get the movement through Input.GetAxis("Mouse X") and if it's not moving , play Idle

Upvotes: 2

Related Questions