【问题标题】:Sprite only moves in one direction when two buttons are held按住两个按钮时,Sprite 只会向一个方向移动
【发布时间】:2021-08-09 03:55:03
【问题描述】:

我试图让我的精灵每隔一段时间移动一个单位。它一直有效,直到同时按住多个键。如果是这种情况,它会朝一个方向移动,具体取决于代码中首先编程的方向。对我来说,似乎我的精灵应该双向移动,因为 if 语句不是 if else 语句。如果我向上并向左移动,它应该向上移动 1 个单位,向左移动 1 个单位。我怎样才能让它做到这一点?

public Transform timmyTransform;
private float timer= 0;
public float movementDelay;


void Update()
{

    timer += Time.deltaTime;
    if (Input.GetAxis("Vertical") < 0 && timer > movementDelay)
    {
        timer = 0;
        timmyTransform.transform.position += new Vector3(0, -1, 0);
    }
    if (Input.GetAxis("Vertical") > 0 && timer > movementDelay)
    {
        timer = 0;
        timmyTransform.transform.position += new Vector3(0, 1, 0);
    }
    if (Input.GetAxis("Horizontal") < 0 && timer>movementDelay)
    {
        timer = 0;
        timmyTransform.transform.position += new Vector3(-1, 0, 0);
    }
    if(Input.GetAxis("Horizontal") > 0 && timer > movementDelay)
    {
        timer = 0;
        timmyTransform.transform.position += new Vector3(1, 0, 0);
    }

    
   

}

【问题讨论】:

  • 嗯,您似乎设置了 timer = 0,因此对 timer &gt; movementDelay 的后续检查将返回 false 并跳过其余说明。 (我认为movementDelay 永远不会是负面的......)
  • 添加到@Alphaharrius 评论,你可能想要一个bool moved,如果你击中其中一个块,将其设置为true,然后最后将计时器归零。

标签: c# visual-studio unity3d


【解决方案1】:

你的问题是timer

您始终将其设置为0,因此在处理第一个按钮按下后,其他条件永远不会满足。

我宁愿做类似的事情,例如

timer += Time.deltaTime;
// Get and store the Input ONCE
var vertical = Mathf.Sign(Input.GetAxis("Vertical"));
var horizontal = Mathf.Sign(Input.GetAxis("Horizontal"));
// directly get the movement as a vector so you can use vector maths
var movement = new Vector2(horizontal, vertical);

// Check whether there currently is any input and timer is due
if (movement.sqrMagnitude > 0 && timer > movementDelay)
{
    timer = 0;

    // directly use the movement as it is already the vector based on the input
    timmyTransform.transform.position += movement;
}

【讨论】:

    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2021-02-26
    • 2017-09-04
    • 2021-07-29
    • 2015-04-24
    • 1970-01-01
    相关资源
    最近更新 更多