Dash towards mouse position going through walls

Hi,

I’m fairly new to unity, I wrote a script for a dash move towards the mouse when left mous button is clicked.
BUT, I used transform for the dash - causing my player object to dash through walls.
I’ve tried Lerp and AddForce(calculating the angle of the mouse click), but couldnt manage to get the same dashing effect from it towards the mouse position.

Any suggestions on how to implement this mechanic?

Here’s the code. first I’m setting the dash time, getting the mouse position, and then getting the vector for it.
Then I execute the dash move.
Also, is it fine using transform.position in a function outside of FixedUpdate? Does the dash results change if used on another computer this way?

    private void DashStart()
    {
        if (Input.GetMouseButtonDown(0))
        {
            dashTime = 0.08f;
            dashTowards = UtilsClass.GetMouseWorldPosition();
            dashTargetPos = (dashTowards - GetPosition()).normalized;
            state = State.Dashing;
        }
    }

    private void Dash()
    {
        float dashSpeed = 40f;
        if (dashTime > 0)
        {
            transform.position += dashTargetPos * dashSpeed * Time.deltaTime;
            dashTime -= Time.deltaTime;
        }
        else if (dashTime <= 0)
        {
            SetStateNormal();
        }
    }

Edit:
Here I changed the velocity. Now dashing only works on the vertical axis for some reason.

 if (dashTime > 0)
        {
            rb.velocity = new Vector2(dashTargetPos.x * dashSpeed, dashTargetPos.y * dashSpeed);
            dashTime -= Time.deltaTime;
        }

You need collision detection for obstacles and player. Whenever you near a wall the collision ca be detected with OnCollisionEnter2D(){} use this to interrupt the dash movement.

It worked!
Thanks man!

hey, I got it the collision detection working, but i don’t really know how to stop that momentum of the dash.
if you could help me with that i would be very grateful.

Hi, it has been two years since than… I don’t really remember.
But, if you want to stop the momentum, you can set the veolcity to zero. (if you want it to stop over time, you can look here: https://stackoverflow.com/questions/40349127/unity-5-how-to-slow-down-rigidbody-naturally-instead-of-sudden-stop)

1 Like