- Home /
How to make Sphere to jump?
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);
}
}
Don't be confused by the code comment, FixedUpdate is not called once per frame.
Answer by AndyMartin458 · Jul 25, 2014 at 06:10 PM
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. http://docs.unity3d.com/ScriptReference/Collider.OnCollisionExit.html
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);
}
Answer by Samael_00001 · Jul 26, 2014 at 11:34 AM
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);
}
}
}
@Samael_00001 I understand that you needed to make modifications, but isn't this equivalent to my answer?
@Samael_00001 Would you be so kind as to make this a comment on my answer and select $$anonymous$$e? It's just proper answers forum etiquette.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Ball jump on collision problem 1 Answer
Increase Jump Through Mouse Clicks? 1 Answer
How do I check when a rigidbody is colliding with the floor? 2 Answers
Movement problem? 0 Answers