- Home /
Setting a Jump Angle Relative to a Surface
Hey, devs! I'm trying to implement some jumping mechanics for a platformer, but I'm a novice when it comes to coding. I'm hoping someone here will be kind enough to help me out.
As it stands, the player — a ball — will jump straight upwards when the Jump button is pressed. This is irrespective of the surface that it’s on, like so:
// JavaScript
var jumpHeight : float = 8;
if (Input.GetButtonDown("Jump") && IsGrounded ()) {
rigidbody.velocity.y = jumpHeight;
}
function IsGrounded () : boolean {
return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.1);
}
A secondary problem with this is that IsGrounded isn’t triggered on steep slopes, leaving the player unable to jump while rolling up and down certain hills.
What I would like — instead of the jump always being directly upwards — is to have the player project off of the surface at a perpendicular angle. For example: Assume level ground is 0°; the jump angle would be 90°, i.e. straight upwards. But if the ground were sloped at 30°, then the jump angle would become 120°. This would even include extremes, like a “180° slope” (for instance, if the ball were rolling on the ceiling during a high-speed loop), wherein the jump becomes 270°, i.e. straight downwards.
This currently goes over my head, though. I've been experimenting and have been able to get the contact points using this code:
// JavaScript
function OnCollisionStay (collision : Collision) {
for (var contact : ContactPoint in collision.contacts) {
}
But from there, I'm not exactly sure what to do. I suspect that I'll need to add velocity or force in the angle between the ball and the contact point, but I'm not sure what practice is best, nor how to do that. Like I said, coding isn't my strength. Is there anyone here with more skill who'd be willing to share their expertise? The lack of this feature is holding back further production on my game, so I'd really appreciate some help.
Answer by hexagonius · Mar 03, 2015 at 05:10 PM
What you can do is get the surface normal. That's the vector you want for the jump direction. Raycast against the collider you receive the contact point of from a distance against it. Get the normal of THAT contact point. Add force along that vector.
Your answer
Follow this Question
Related Questions
Player sticks to ground occasionally after trying to jump 0 Answers
Custom Collision Detection 4 Answers
Trying to Disable Compenent when there's a collsion 2 Answers
Collision not working. 1 Answer