#Need help for holding mouse to move character

1 messages · Page 1 of 1 (latest)

stuck cobalt
#

I have this script which move the character toward the clicked position of the mouse.
How do I make it keep moving toward the mouse when the mouse is still being pressed ?

    {
        mouseClickAction.Enable();
        mouseClickAction.performed += Move;
    }

    private void OnDisable()
    {
        mouseClickAction.performed -= Move;
        mouseClickAction.Disable();

    }

    private void Move(InputAction.CallbackContext context)
    {
        Ray ray = mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue());
        if (Physics.Raycast(ray: ray, hitInfo: out RaycastHit hit) && hit.collider)
        {
            if (coroutine != null) StopCoroutine(coroutine);
            coroutine = StartCoroutine(PlayerMoveToward(hit.point));
        }
    }

    private IEnumerator PlayerMoveToward(Vector3 target)
    {
        float playerDistanceToFloor = transform.position.y - target.y;
        target.y += playerDistanceToFloor;
        while(Vector3.Distance(transform.position, target) > 0.1f)
        {
            Vector3 destination = Vector3.MoveTowards(transform.position, target, playerSpeed * Time.deltaTime);
            Vector3 direction = target - transform.position;
            /*transform.position = destination;*/

            

            rb.velocity = direction.normalized * playerSpeed;
            animator.SetBool("isRunning", true);

            if (Vector3.Distance(transform.position, target) < 0.5f)
            {
                rb.velocity = direction.normalized * 0;
                animator.SetBool("isRunning", false);
            };

            //transform.rotation = Quaternion.LookRotation(direction.normalized);
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction.normalized), rotationSpeed * Time.deltaTime);

            

            yield return null;
        }
    }```