I am trying to get a gameobject to ‘jump’ with a nice arc and such, to a point that is clicked on the screen (in the world). The idea is to jump the game object from platform to platform.
I have this semi working but when I click on a platform sometimes I go toward it, sometimes I go in some random direction, other times I jump right toward the right place, but fly right through it, even with colliders.
So my question is 2 fold. 1st is how to make this work properly. 2nd is how to get the jumping object to stop moving and stay on the platform (no sliding off).
Here is my code, it is simply placed on the game object I need to ‘jump’:
public class JumpOnClick : MonoBehaviour {
public float angle = 25;
void Update(){
if(Input.GetMouseButtonUp(0))
{
Vector3 force = JumpForce(getClickPoint(),angle);
rigidbody.AddForce (force,ForceMode.Impulse);
Debug.Log("Force " + force);
}
}
Vector3 getClickPoint()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 point = ray.origin + ray.direction;
return point;
}
Vector3 JumpForce(Vector3 dest, float angle){
var dir = dest - transform.position; // get target direction
var h = dir.y; // get height difference
dir.y = 0; // retain only the horizontal direction
var dist = dir.magnitude ; // get horizontal distance
var a = angle * Mathf.Deg2Rad; // convert angle to radians
dir.y = dist * Mathf.Tan(a); // set dir to the elevation angle
dist += h / Mathf.Tan(a); // correct for small height differences
// calculate the velocity magnitude
var vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
return vel * dir.normalized * rigidbody.mass;
}
}