我是Unity和c#的新手。我正在创建一个手机项目。我只想在喷气机升起时通过左右触摸来移动喷气机Axis位置
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
switch (touch.phase)
{
case TouchPhase.Began:
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
//side to side movement
if (touch.position.x < Screen.width / 2)
rb.velocity = new Vector2(- 2f, transform.position.y);
if (touch.position.x > Screen.width / 2)
rb.velocity = new Vector2(+ 2f, transform.position.y);
}
break;
case TouchPhase.Ended:
rb.velocity = new Vector2(0f, 0f);
break;
}
喷气机具有Addforce,因此当我左右触摸时,喷气机速度会降低。
喷气机代码:
switch (JetOn)
{
case true:
StartCoroutine(BurnFuel());
rb.AddForce(new Vector2(0f, JumpForce), ForceMode2D.Force);
break;
case false:
rb.AddForce(new Vector2(0f, 0f), ForceMode2D.Force);
break;
}
答案 0 :(得分:0)
请勿混用AddForce
并手动分配给velocity
。直接分配给velocity
会使AddForce
行为异常,并经常导致它永远无法工作。
选择一个,然后将其用于制作该帧所需的每个速度变化。
以下是您的代码示例,仅分配给velocity
:
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
switch (touch.phase)
{
case TouchPhase.Began:
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
//side to side movement
if (touch.position.x < Screen.width / 2)
// I think you mean rb.velocity.y here instead of transform.position.y
rb.velocity = new Vector2(- 2f, rb.velocity.y);
if (touch.position.x > Screen.width / 2)
rb.velocity = new Vector2(+ 2f, rb.velocity.y);
}
break;
case TouchPhase.Ended:
rb.velocity = new Vector2(0f, 0f);
break;
}
}
...
switch (JetOn)
{
case true:
StartCoroutine(BurnFuel());
rb.velocity += new Vector2(0f, JumpForce) / rb.mass;
break;
case false:
// unnecessary but included for example purposes
// rb.velocity += new Vector2(0f, 0f) / rb.mass;
break;
}