I don’t know, how to find out if a Phere is already in the air (we can jump only when we are on a ground, right?)
Thanks!!
I’m using this script to move along:
using UnityEngine;
using System.Collections;
public class BallMovement : MonoBehaviour {
public float speed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rigidbody.AddForce(movement * speed * Time.deltaTime);
}
}
I assume that your sphere has a collider? You can do a check for when it is on the ground with OnCollision commands. Try this. Unity - Scripting API: Collider.OnCollisionExit(Collision)
bool isGrounded = false;
void OnCollisionEnter(Collider other)
{
if(other.gameObject.tag == "ground")
isGrounded = true;
}
void OnCollisionExit(Collider other)
{
if(other.gameObject.tag == "ground")
isGrounded = false;
}
Also, nothing in your code seems to keep you from jumping while you are already in the air. Maybe something like this?
Vector3 movement = Vector3.zero;
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
//Don't allocate new memory in FixedUpdate!!!!!
movement.x = moveHorizontal;
movement.z = moveVertical;
if(isGrounded == true)
rigidbody.AddForce(movement * speed * Time.deltaTime);
}
Here is my Solution:
using UnityEngine;
using System.Collections;
public class BallMovement : MonoBehaviour {
public float speed;
public float jumpSpeed;
bool CanJump;
bool jump;
void Start ()
{
CanJump = true;
jump = false;
}
void OnCollisionExit(Collision collisionInfo)
{
CanJump = false;
jump = false;
}
void OnCollisionEnter(Collision collisionInfo)
{
CanJump = true;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && CanJump == true)
{
jump = true;
}
}
void FixedUpdate () {
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rigidbody.AddForce(movement * speed * Time.deltaTime);
if (jump == true)
{
rigidbody.AddForce(Vector3.up * jumpSpeed);
}
}
}