【问题标题】:C# unity rigidbody 2D restrict movement to only one axis at the same timeC# unity 刚体 2D 将运动限制在同一时间仅一个轴
【发布时间】:2021-05-31 14:14:05
【问题描述】:

我正在制作 2d 游戏,但我遇到了控制问题。我正在尝试让玩家只能水平和垂直移动,如果我同时按下 2 个控制按钮,例如 w 和 d,让玩家在你按下的第二个按钮对应的方向上移动,它适用于 Vertical ,但是如果我在向上移动时按例如 d 它只会继续向上移动,而它必须向右移动。代码如下:

  {
   public Vector2 movement;
   void Update()
   {
     movement.x = Input.GetAxisRaw("Horizontal");
     movement.y = Input.GetAxisRaw("Vertical");
     if (movement.y != 0)
     {
         movement.x = 0;
     }
     if (movement.x != 0)
     {
         movement.y = 0;
   }
  }```

【问题讨论】:

  • 那么在这种情况下if (movement.y != 0) { movement.x = 0; } 开始了,你只保持垂直移动
  • 我该如何解决?

标签: c# unity3d controls


【解决方案1】:

一个简单的解决方案是设置一个标志,指示哪个键(或轴)首先接收输入。在这种情况下,您必须在帧之间存储此信息。 在这种情况下,单个布尔值 afaik 是不够的(因为它只代表两种状态),但我们可以简单地使用枚举来提供必要的容器来存储我们的信息:

   // States/Prio of (first) user input
   public enum PrioritisedInput
   {
    None,
    XAxis,
    YAxis
   }
  
   public PrioritisedInput prioInput = PrioritisedInput.None;

   public Vector2 movement;
   void Update()
   {
     movement.x = Input.GetAxisRaw("Horizontal");
     movement.y = Input.GetAxisRaw("Vertical");

     if(movement.y == 0 && movement.x == 0)
     {
      // Reset value if no input was detected
      prioInput = PrioritisedInput.None;         
     }
     else if(movement.y != 0 && movement.x == 0)
    {
     // YAxis input, but no xAxis input. Prio YAxis
     prioInput =  PrioritisedInput.YAxis;
    }
    else if(movement.y == 0 && movement.x != 0)
    {
     // YAxis input, but no xAxis input. Prio XAxis
     prioInput =  PrioritisedInput.XAxis;
    }
    else if(movement.y != 0 && movement.x != 0 && prioInput == PrioritisedInput.None)
    {
     // What happens if both axis receive an input the same frame?
     // Maybe just prio x axis
     prioInput =  PrioritisedInput.XAxis;
    }    

     if (prioInput == PrioritisedInput.XAxis)
     {
         movement.y = 0;
     }
     else if(prioInput == PrioritisedInput.YAxis)
     {
         movement.x = 0;
     }

阅读有关枚举的更多信息:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum

【讨论】:

  • 有什么错误?显然,如果没有 ide 或任何东西,语法可能不会 100%。请分享错误消息,否则我无能为力
  • 我可以发截图但是我的VS是俄语的。
  • 真的不知道该说什么。也许复制粘贴代码?或者你使用俄语字母之类的东西?那么我无法帮助您处理您的代码。如果您可以将 Visual Studio 设置为英文,然后复制粘贴错误消息也会有所帮助
  • 他们中的大多数都在我身上,但仍然剩下 1 个 CS0103 名称“无”在此上下文中不存在 else if (movement.y != 0 && motion.x != 0 && prioInput == None )
  • 是的,正如我所说,它可能不是 100% 语法正确。如果您只是复制所有代码,然后遇到错误然后不假思索地辞职,那么您将找不到 100% 适合您需求的解决方案。检查一下我写的:else if(movement.y != 0 && movement.x != 0 && prioInput == None) 显然“无”不存在。它需要是 PrioritisedInput.None
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 2016-05-22
相关资源
最近更新 更多