Limit mouse position so that player launches same distance

Player dashes towards the mouse position, however, lets say you put the cursor far-right like x(20) so player moves 20mt but if you put it x(5) player dashes 5mt how can I limit the pos. input so the player would travel the same distance no matter the mouse position distance.

I want to get the mouse direction and launch the player same distance no matter the mouse position distance.

    //this is inside the Fixed Update method.
    float xor = Input.GetAxis("Horizontal"), yor = Input.GetAxis("Vertical");

    if ((xor != 0 || yor != 0) && !dash)
    {
        rg2d.velocity = new Vector2(xor * speed, yor * speed);
        anim.SetFloat("speed", Mathf.Abs(xor + yor));
    }
    if(Input.GetKeyDown(KeyCode.Mouse0) && !fire)
    {
        //PUNCH
        dash = true;
        fire = true;
        StartCoroutine(Stop_Fire(0.5f));
        anim.SetTrigger("attack");
        fist.GetComponent<Collider2D>().enabled = true;

        Vector2 pos = (transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition)).normalized;

        rg2d.AddForce(-pos * punch_force, ForceMode2D.Impulse);
    }

//I call this function at the end of the attack animation.in the Animation window
public void Stop_Dash()
{
    dash = false;
    fire = false;
    fist.GetComponent<Collider2D>().enabled = false;
    rg2d.velocity = Vector2.zero;
}

well clamping is not the right solution that is correct. Try the following line instead:

Vector2 pos = transform. position + (transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition)).normalized * yourMaximumDashDistance;

you will probably have to adjust some values ot get the right distance but this should result in a “clamped relative position” to your character.

Share the result :slight_smile:

The problem was the mouse input z-axis. it was unused but still had a big value that effected the normalization.

instead of :

Vector2 pos = (transform.position Camera.main.ScreenToWorldPoint(Input.mousePosition)).normalized;

this should be used:

Vector3 mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 moveDirection = (transform.position - mousepos);
moveDirection.z = 0;
moveDirection.Normalize();

rg2d.AddForce(-moveDirection * punch_force, ForceMode2D.Impulse);