- Home /
Why the ball is not jumping in direction
Following a tutorial I was able to make a simple ball jump. However the ball jumps only on y direction and only when on the ground. My question is why the ball is not jumping when it's moving or why doesn't jump in the direction of movement (left or right). Here is how I coded:
using UnityEngine;
using System.Collections;
public class BallControl : MonoBehaviour {
// Use this for initialization
public float rotationSpeed = 100;
public float jumpHeight = 8;
private bool isFalling = false;
// Update is called once per frame
void Update ()
{
//-----------Handle ball rotation
float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
rotation *= Time.deltaTime;
GetComponent<Rigidbody>().AddRelativeTorque(Vector3.back * rotation);
if(Input.GetKeyDown(KeyCode.Space) && isFalling == false)
{
GetComponent<Rigidbody>().velocity = new Vector3(0, jumpHeight, 0);
}
isFalling = true;
}
void OnCollisionStay()
{
isFalling = false;
}
}
Answer by tanoshimi · Oct 26, 2016 at 07:50 AM
It only jumps when you are on the ground because of isFalling == false
check on line 20, which is only true if you are currently in a collision with something (line 30).
It only jumps straight up because on line 22, you are setting the y velocity to jumpheight, but both the x and z components of velocity to 0: GetComponent<Rigidbody>().velocity = new Vector3(0, jumpHeight, 0);
But i don't want the x and z to have velocities. I want the ball to jump in horizontal direction if I am pressing the arrow keys. Else just up direction.
As @tanoshimi said, you are overwriting your horizontal direction completely by setting the x & z values to 0. That means your ball will allways stop it's x & z trajectory when you press the jump button. You should use AddForce or something like
GetComponent<Rigidbody>().velocity = new Vector3(velocity.x, jumpHeight, velocity.z)
(with the 'velocity' being the correct rigidbody velocity) ins$$anonymous$$d.
Thanks for the guide. I rewrote my code like this:
GetComponent<Rigidbody>().velocity = new Vector3(GetComponent<Rigidbody>().velocity.x,jumpHeight,GetComponent<Rigidbody>().velocity.z);
And now it works fine.
Your answer
Follow this Question
Related Questions
When I jump i teleport up and then glide down 0 Answers
Another Slow Fall Problem... 2 Answers
Jump character with click on space key in Javascript 1 Answer
Jumping only once (2D) 2 Answers