
It looks like you're new here. If you want to get involved, click one of these buttons!
I am doing Brackeys Unity coursehttps://www.youtube.com/watch?v=r5NWZoTSjWs&list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6&index=11 And for my level 2 I tried to make a cube jump using the space key, this works fine. However by holding space the cube flies. Can someone please help me solve this problem🙄
Take your old code and change
Input.GetKey("Space")
to
Input.GetKeyDown("Space")
it is causing because when we are holding spacebutton, the if block is executed each frame and force is added each frame.
But the change will allow the force to apply only when key is pressed down, on ly one time. Next time when key is again pressed down.
Answers
Can we see your code
Here is my First one in which the cube flies if I hold space
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
public float upwardsForce = 100f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if(Input.GetKey("d"))
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if(Input.GetKey("a"))
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if(rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
if(SceneManager.GetActiveScene().buildIndex != 0)
{
if (Input.GetKey("space") )
{
rb.AddForce(0, upwardsForce * Time.deltaTime, 0, ForceMode.VelocityChange);
}
}
}
}
And this is my new one which I thought would solve the problem but the cube doesn't even jump in this
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
public float upwardsForce = 100f;
public bool cubeOn = true;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if(Input.GetKey("d"))
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if(Input.GetKey("a"))
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if(rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
if(SceneManager.GetActiveScene().buildIndex != 0)
{
if (Input.GetKey("space") && cubeOn)
{
rb.AddForce(new Vector3(0, upwardsForce * Time.deltaTime, 0), ForceMode.Impulse);
cubeOn = false;
}
}
}
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Ground")
{
cubeOn = true;
}
}
}
Thanks
Welcome