#how can i make the player dashes towards the mouse position in unity 3d?

12 messages · Page 1 of 1 (latest)

royal tree
#

[]cb

little martenBOT
#

Use codeblocks to send code in a message!

To make a codeblock, surround your code with ``` (3 backticks. Click here to see where the key is)

To use syntax highlighting, add the file extension of the language you wish to highlight (cs for C#, cpp for C++)

For example:
```cs
Console.WriteLine("Hello World");
```

Produces:

Console.WriteLine("Hello World");

To send lengthy code, paste it into https://paste.myst.rs/ and send the link of the paste into chat.

fossil compass
#

public class PlayerDash : MonoBehaviour
{
    public float dashSpeed = 10f;  // Speed of the dash
    public float dashTime = 0.2f;  // Duration of the dash

    private Rigidbody rb;
    private bool isDashing = false;
    private float dashTimer;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0) && !isDashing)
        {
            Vector3 mousePosition = GetMouseWorldPosition();
            StartDash(mousePosition);
        }

        if (isDashing)
        {
            dashTimer -= Time.deltaTime;
            if (dashTimer <= 0)
            {
                StopDash();
            }
        }
    }

    void StartDash(Vector3 targetPosition)
    {
        isDashing = true;
        dashTimer = dashTime;

        Vector3 dashDirection = (targetPosition - transform.position).normalized;
        rb.velocity = dashDirection * dashSpeed;
    }

    void StopDash()
    {
        isDashing = false;
        rb.velocity = Vector3.zero;
    }

    Vector3 GetMouseWorldPosition()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            return hit.point;
        }
        return Vector3.zero;
    }
}
royal tree
#

It seems like you've done a lot of code already, this is good

#

Can you be more specific with what you want help with?

fossil compass
halcyon crown
#

The code looks correct to me at first glance. How does your code missbehave? Maybe you have frozen position constraints on your rigidbody component?

sturdy heart
#

A video to look at for some ideas

fossil compass
halcyon crown
#

What I meant is what is your code doing right now. Is it even moving on any direction? Is is moving at all when you click?

fossil compass