所以我使用 unity 并且我希望我的物件在玩家按下空間時占據高度
但現在他只是跳躍,你必須有垃圾郵件空間才能飛走
有人可以幫我嗎?
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);
}
}
uj5u.com熱心網友回復:
Input.GetKeyDown 僅在按下按鈕的單個幀中為真。
在用戶開始按下由 key
KeyCode enum引數標識的鍵的幀期間回傳 true 。
您正在尋找的是當按鈕保持按下狀態時每一幀Input.GetKey都是真的。
當用戶按住key
KeyCode列舉引數標識的鍵時回傳 true 。
此外,您絕對不希望在while那里回圈!在回圈中的值spacePressed將永遠不會改變=>無限回圈=>應用程式崩潰!
你只是想做
// 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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/359539.html
上一篇:d3JS云圖:避免單詞重疊
