few notes:

  1. I'm new to game development
  2. I'm not new to developing (1 year of front end web development)

I'm trying to get my character to launch towards mouse left click button (which I understood to be translated into screen onclick once its exported to mobile) I've got the following code down (used the web for help)

move speed is a float that's equal to 10 in this example

if (Input.GetMouseButton (0)) {
        mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        direction = (mousePosition - transform.position).normalized;
        rb.velocity = new Vector2 (direction.x * moveSpeed, direction.y * moveSpeed);

Which works great, but has 2 issues: If I keep holding leftMouseButton my character is pinned to the cursor I want a single, gravity affected, launch (jump of sort) towards my mouse button.

This is all under the Update() function.

  • 1
    \$\begingroup\$ Note that once your player character is affected by gravity, a jump directly toward the mouse cursor won't necessarily lead to the character reaching the mouse cursor, as gravity will pull them down off the straight-line path to the mouse. It's possible to plan a parabolic trajectory through a target position, if that's preferred \$\endgroup\$
    – DMGregory
    Aug 11, 2019 at 12:39

1 Answer 1


Your condition, Input.GetMouseButton(0), will be true for as long as that button is held down. Your code therefore updates the velocity of your Rigidbody2D to move it towards the target (tap position) while the button is held down / a tap on the screen is held, which is what produces your 'pinned to the cursor' behaviour.

Depending which phase (input started / completed) you want to trigger on, GetMouseButtonDown or GetMouseButtonUp can be used for reading button state changes. These will only return true once per press, unlike the ongoing GetMouseButton.

To perform an immediate change in velocity, "...such as forces from explosions or collisions." ForceMode2D.Impulse is useful, in conjunction with Rigidbody2D.AddForce (also applicable to the other similar methods on Rigidbody2D). The default ForceMode2D (ForceMode2D.Force) is for applying force continuously, each FixedUpdate.

As an example, to make a Rigidbody2D rb2d jump towards some point target with a magnitude of jumpMagnitude, you could use:

Vector2 heading = target - rb2d.position;
Vector2 direction = heading / heading.magnitude;
rb2d.AddForce(direction * jumpMagnitude, ForceMode2D.Impulse);
  • \$\begingroup\$ Now i've got a different problem my function suddenly only shots me up, not to the sides... \$\endgroup\$
    – Liad Goren
    Aug 11, 2019 at 17:07
  • \$\begingroup\$ @LiadGoren Are you using a perspective camera? \$\endgroup\$
    – Joe
    Aug 11, 2019 at 18:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .