Home > database >  I want to make a method that returns the position the player is facing
I want to make a method that returns the position the player is facing

Time:06-06

I made a simple script to check what position the player is facing a put that in my animator

1 = up

2 = right

3 = down

4 = left

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);

then I get the error

Assets/Scripts/PlayerMovement.cs(21,25): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'Vector2', with 2 out parameters and a void return type.

CodePudding user response:

I believe your issue comes with how you are trying to use your switch statement as Vector(1,0) is attempting to call a function not actually reference the value you are looking a viable alternative is to use when like in the following example

                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;

I'm also using the shorthand up, left, right and down instead of defining the values manually

CodePudding user response:

Assuming velocity is of type Vector2 you can't set the values of x and y as they are read-only properties.

Use this instead:

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

CodePudding user response:

Vectors are structs and you can't create them without using new e.g. case new Vector2(0f, 1f):. There are some ready made constants for direction built in that you can use:

switch(velocity){
    case Vector2.up:
    direction = 1;
    break;
    case Vector2.right:
    direction = 2;
    break;
    case Vector2.down:
    direction = 3;
    break;
    case Vector2.left:
    direction = 4;
    break;
}
  • Related