icecub
icecub

Reputation: 8773

Getting the player jump correctly in Unity3D

I'm still learning the basics so please be a bit gentle. I'm working on the movement script of a roll-a-ball game. I've got the rolling around working perfectly fine, but now I'm trying to add the ability to jump.

In my case the "player" is a basic Sphere. What I'm trying to accomplish is that when space is pressed, the ball leaps into the air in the direction it's currently rolling.

This is what I've tried myself, but gave very strange results:

float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");

Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

if (Input.GetKey("space"))
{
    transform.position += transform.up * 20 * Time.deltaTime;
}

rb.AddForce(movement * speed); //rb = RigidBody

This resulted in the ball sometimes jumping in the wrong direction or simply just speeding into some direction without jumping at all. So obviously I'm getting closer, but not quite there yet. Could anyone explain what I'm doing wrong and how to fix it?

Not looking for a quick fix! Don't learn anything from that.

Upvotes: 2

Views: 3635

Answers (2)

user5834380
user5834380

Reputation: 1

To add to the accepted answer: The jumping into random directions issue could have been caused by the transform.up. That vector is the up direction relative to your current transform. That's usually the same as the actual up direction, except if you rotate the game object. And as the object happens to be a rolling ball in this case, it's very likely that it's rotated.

You can fix it by using the global up direction instead - either by doing it like in the accepted answer or by using Vector3.up.

Upvotes: 0

Tom
Tom

Reputation: 2472

Have a try at this :)

if (Input.GetKey("space"))
{
    rigidbody.AddForce(new Vector3(0, yourJumpForce, 0), ForceMode.Impulse);
}

You also might want to fiddle with the gravity settings in the rigidbody to get your desired jump as well!

EDIT Explanation:

I think it may be because you are applying you movement to your Rigidbody, but your jumping method to the Transform itself.

A Rigidbody is a physics component (see docs.unity3d.com/ScriptReference/Rigidbody.html), where a Transform is to do with position, rotation and scale.

A jump could be considered a physics problem - therefore altering the jump is to do with physics (Rigidbody), not the position (Transform). I tend to do all movement code with the Transform, as you are moving positions, and do all physics based work with the Rigidbody, as you are applying physics to the GameObject! :)

Upvotes: 1

Related Questions