【问题标题】:I want to make a method that returns the position the player is facing我想做一个方法来返回玩​​家所面临的位置
【发布时间】:2022-06-14 00:07:06
【问题描述】:

我制作了一个简单的脚本来检查玩家面对的位置并将其放入我的动画师中

1 = 向上

2 = 正确

3 = 向下

4 = 左

private Vector2 velocity;
private Animator animator;
private int direction;
private void Awake() {
    animator = GetComponent<Animator>();

}
void Update(){
    velocity.x = Input.GetAxisRaw("Horizontal");
    velocity.y = Input.GetAxisRaw("Vertical");
    switch(velocity){
        case Vector2(0,1):
        direction = 1;
        break;
        case Vector2(1,0):
        direction = 2;
        break;
        case Vector2(0,-1):
        direction = 3;
        break;
        case Vector2(-1,0):
        direction = 4;
        break;
    }
    animator.SetFloat("Facing",direction);

然后我得到错误

Assets/Scripts/PlayerMovement.cs(21,25):错误 CS8129:没有为类型“Vector2”找到合适的“解构”实例或扩展方法,具有 2 个输出参数和 void 返回类型。

【问题讨论】:

    标签: c# unity3d switch-statement vector2


    【解决方案1】:

    我相信您的问题与您尝试使用 switch 语句的方式有关,因为 Vector(1,0) 正在尝试调用一个函数而不是实际引用您正在寻找的值一个可行的替代方法是使用 when 就像在下面的例子

                    case Vector2 v when v.Equals(Vector2.up):
                        Debug.Log("Up");
                        break;
                    case Vector2 v when v.Equals(Vector2.left):
                        Debug.Log("Left");
                        break;
                    case Vector2 v when v.Equals(Vector2.back):
                        Debug.Log("Back");
                        break;
                    case Vector2 v when v.Equals(Vector2.right):
                        Debug.Log("Right");
                        break;
    

    我还使用简写 upleftrightdown,而不是手动定义值

    【讨论】:

      【解决方案2】:

      假设velocityVector2 类型,您不能设置xy 的值,因为它们是只读属性。

      改用这个:

      velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
      

      【讨论】:

        【解决方案3】:

        向量是结构体,如果不使用new,则无法创建它们,例如case new Vector2(0f, 1f):。您可以使用一些现成的内置方向快捷方式:

            if(velocity == Vector2.up)
            {
                print("direction = 1");
            } else if (velocity == Vector2.right)
            {
                print("direction = 2");
            } else if (velocity == Vector2.up)
            {
                print("direction = 3");
            } else if (velocity == Vector2.down)
            {
                print("direction = 4");
            } else if (velocity == Vector2.left)
            {
                print("direction = 1");
            }
        

        【讨论】:

        • 它给了我错误 Assets/Scripts/PlayerMovement.cs(24,18): error CS0150: A constant value is expected
        • 在哪一行代码上?
        • Vector2 的情况....:
        • 是的,你是对的。我的错,你必须改用 IF 语句,更新答案。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        • 1970-01-01
        • 2021-08-24
        • 1970-01-01
        相关资源
        最近更新 更多