Sorry for the newbie question, but there is something I really can’t figure out myself.
I’m trying to make a scene with a cube that can jump and move when you press the corresponding arrow keys.
I’m using OnCollisionStay and an if statement to only let the cube jump when colliding with the plane below it, so it doesn’t jump an insane amount of time, or jump in midair. When I run the scene, the cube falls on to the plane, and the OnCollisionEnter function runs, but after a few seconds, it stops running and you can’t jump. I don’t know what I’m doing wrong, can someone help?
Here’s my code.
using UnityEngine;
using System.Collections;
public class MoveCube : MonoBehaviour {
//Variables
public float movementSpeed = 0.3f;
Rigidbody c_rigidbody;
void Start() {
c_rigidbody = GetComponent<Rigidbody>();
StartCoroutine (Movement ());
}
IEnumerator Movement(){
while (3 == 3) {
//Sets variables to key codes.
bool forward = Input.GetKey (KeyCode.UpArrow);
bool backward = Input.GetKey (KeyCode.DownArrow);
bool left = Input.GetKey (KeyCode.LeftArrow);
bool right = Input.GetKey (KeyCode.RightArrow);
//Asks if keys are being pressed. If "yes", moves object's transform.
if(forward){
transform.Translate (Vector3.forward * movementSpeed);
}
if(backward){
transform.Translate (Vector3.back * movementSpeed);
}
if(left){
transform.Translate (Vector3.left * movementSpeed);
}
if(right){
transform.Translate (Vector3.right * movementSpeed);
}
yield return null;
}
}
//If collision: tells console "Colliding." & Adds upward force to provide a "jump".
void OnCollisionStay(Collision collision){
Debug.Log ("Colliding.");
if (Input.GetKey (KeyCode.Space)) {
c_rigidbody.AddForce (Vector3.up * 500.0f);
}
}
}
Thanks so much for your help.