Help with launching object in direction

Hey everyone! I’m working on a mechanic that allows the player to jump in the direction of the mouse, and this is what I’ve got.

Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
mousePos = new Vector3(mousePos.x, mousePos.y, 0);
Vector3 pos = new Vector3(transform.position.x, transform.position.y, 0);

dir = (mousePos - pos).normalized;
airMotion = dir * jumpForce;

In my game you will be facing a wall and need to click to launch yourself in said direction, and your y-rotation will change depending on whatever wall you’re facing. My problem is that my code currently allows you to jump towards the player-mouse direction but only if you’re facing the z-axis and I need to be able to jump in the direction regardless of your rotation. Thanks for the help.

At the moment, you’re zeroing out the Z-axis, so there’s nothing strange about being unable to apply this to that axis in its current form.

First off, the mouse cursor isn’t being given any specific depth constraint. This can be done in a few ways, such as

  1. basing it on the camera’s depth limits,

  2. performing a raycast to the mouse position, or by

  3. constraining the world position of the mouse cursor yourself by projecting the vector onto a plane (or this function, specifically).

Well, the first option is the least likely to fit your exact intent, due to the variable nature of camera depth values and the second will generally result in an accurate position in the world where the mouse is pointing. However, you already presumably know at what depth you want to aim – Perpendicular to the camera. So, let’s go with option 3:

Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
Vector3 planeNormal = -cam.forward;

mousePos = Vector3.ProjectOnPlane(mousePos, planeNormal);
Vector3 pos = Vector3.ProjectOnPlane(transform.position, planeNormal);

dir = (mousePos - pos).normalized;
airMotion = dir * jumpForce;