So i use unity and i want my object to take height for as long as the player presses space
But for now he simply jumps and you gotta spam space for it to fly away
Could someone help me ?
private Rigidbody2D rb;
public float Speed;
private bool spacePressed;
public float jetForce;
pivate void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
spacePressed = true;
}
else
{
spacePressed = false;
}
Move();
Jet();
}
private void Move()
{
float x = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(Speed * x, rb.velocity.y);
}
private void Jet()
{
while (spacePressed == true)
{
rb.velocity = new Vector2(rb.velocity.x, jetForce);
}
}
CodePudding user response:
Input.GetKeyDown
is only true in the one single frame where the button was pressed down.
Returns true during the frame the user starts pressing down the key identified by the key
KeyCode enum
parameter.
What you are looking for is Input.GetKey
which is true every frame while the button stays pressed.
Returns true while the user holds down the key identified by the key
KeyCode
enum parameter.
Further you definitely do NOT want a while
loop there! Inside the loop the value of spacePressed
will never change => infinite loop => app crash!
You rather simply want to do
// Do continuous physics based things in FixedUpdate, not in Update!
// if there WAS any single event based user input then yes, do it in Update with a field for it
// later handle it in FixedUpdate (not the case here though since there are now only two continuous inputs)
private void FixedUpdate()
{
Move();
Jet();
}
private void Move()
{
var velocity = rb.velocity;
velocity.x = Input.GetAxis("Horizontal") * Speed;
rb.velocity = velocity;
}
private void Jet()
{
// since this method is anyway already called every physics frame
// there is no need for
// - a while loop here
// - getting this now continuous user input in Update
if(Input.GetKey(KeyCode.Space))
{
rb.velocity = new Vector2(rb.velocity.x, jetForce);
}
}