How do I change my character from idle animation to running animation while i hold a key, In C#?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ZeroCrits

// here is what i tried but i have no idea what to use to change from one animation to

//another

using Godot;
using System;
public class Movement : KinematicBody2D
{
// Declare member variables here. Examples:
// private int a = 2;
// private string b = “text”;
[Export]public int speed = 480;
public int limit = 800;
public Vector2 velocity = new Vector2();

public void GetInput(){
velocity = new Vector2();

if (Input.IsActionPressed(“right”)){
velocity.x += 50;
AnimationPlayer.}
if (Input.IsActionPressed(“left”)){
velocity.x -= 50;
AnimationPlayer.Play(“run right”);}
if(Input.IsActionPressed(“down”)){
velocity.y += 50;
AnimationPlayer.play();}
if(Input.IsActionPressed(“up”)){
velocity.y -= 50;
AnimationPlayer.play();}
if(Input.IsActionPressed(“shift”) && Input.IsActionPressed(“right”)){
velocity.x += 150;
AnimationPlayer.play();
AnimationPlayer.(“run right”);
}
if(Input.IsActionPressed(“shift”) && Input.IsActionPressed(“left”)){
velocity.x -= 150;
AnimationPlayer.play();}
AnimationPlayer.Play(“idle”);
}
public override void _PhysicsProcess(float delta)
{
GetInput();
velocity = MoveAndSlide(velocity);
}
}

:bust_in_silhouette: Reply From: SawmillTurtle

Try this:

First, declare an enum at the start of your code, like so:

enum myKeys { //you can name this whatever
none = 0;
right = 1;
left = 2;
down = 3;
up = 4;
shiftRight = 5;
shiftLeft = 6;
}

Now place this in GetInput. Make sure to place the necessary code where it needs to go and don’t just COPY-PASTE over everything:

int keyPressed = myKeys.none;
if (Input.IsActionPressed("right")
{
if (Input.IsActionPressed("shift")
{
keyPressed = myKeys.shiftRight;
}
else
{
keyPressed = myKeys.right;
}
}
if (Input.IsActionPressed("left")
{
if (Input.IsActionPressed("shift")
{
keyPressed = myKeys.shiftLeft;
}
else
{
keyPressed = myKeys.left;
}
}
if (Input.IsActionPressed("up")
{
keyPressed = myKeys.up;
}
if (Input.IsActionPressed("down")
{
keyPressed = myKeys.down;
}
switch(keyPressed)
{
case 0:
/*Idle goes here. Will only execute if 'keyPressed' has not been changed from default value, which means that no keys are being pressed. Obviously. */
break;

case 1:
//right
break;

case 2:
//left
break;

case 3:
//down
break;

case 4:
//up
break;

case 5:
//right + shift
break;

case 6:
//left + shift
break;

default:
//in case we end up with a number we didn't expect, which should never happen
break;
}

Hope this helps. Just remember to set things up in your switch statement under case 0, or this will all have been for nothing. LMK if you have any problems. I haven’t tested this code, but logically it should work.