How do I launch my 2D player toward my mouse position?

Viewed 23

I'm trying to implement a mechanic where while I hold down right-mouse button near an object, time slows, allowing you to aim where you want to launch, then on mouse button up, time continues and the player gets launched toward where the mouse cursor is on screen. For some reason, my code results in the player only flying upward. I don't understand why. I've tried everything I can think of and nothing works.

    if (Input.GetMouseButton(1))
            {
                Debug.Log("checking for 'launcher spike...' ");
                if (inSpikeRange == true)
                {
                    Debug.Log("in slo-mo");
                    //slow down time 
                    Time.fixedDeltaTime = 1.5f;
                    Time.timeScale = 0.03f;
                }
            }
            if (Input.GetMouseButtonUp(1))
            {
                if (inSpikeRange == true)
                {
                    Debug.Log("launch!");
                    //speed up time
                    //launch player
                    Time.fixedDeltaTime = 0.02f;
                    Time.timeScale = 1f;
                    Vector2 launchDirection = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x - transform.localPosition.x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y - transform.localPosition.y);
    
rb.AddForce(launchDirection * spikeLaunchForce, ForceMode2D.Impulse);
                }
            }

Any suggestions would be super helpful. Thanks in advance!

1 Answers

Make sure your camera is orthographic and also change the code as below.

if (Input.GetMouseButtonUp(1) && inSpikeRange)
{
    Vector2 launchDirection = (Camera.main.ScreenPointToRay(Input.mousePosition).GetPoint(1) - transform.position).normalized;

    rb.AddForce(launchDirection * spikeLaunchForce, ForceMode2D.Impulse);
}
Related