How do I make a ball move only with 4 keys?

Hey,

I’m trying make a game. It is made so it has an option to play 4 players at once on 1 computer. So what i need is to make the balls move, one with WASD, one with arrows, one with UHJK and one with GVBN or something like that. But I don’t know how :-/ I made this

void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis (“Horizontal”);
float moveVertical = Input.GetAxis (“Vertical”);

Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

rb.AddForce (movement * speed);

It moves with WASD and arrows but i want one that i can easily change so i can make 4 scripts to with the different keycodes.

Help is very apprecaited! Thanks!

There’s lots of ways of doing this, but the simplest (I think) would be to just have a variable that defines which player the ball belongs to, and get input based off that. You’ll first need to setup separate movement axes for each player (use the InputManager in Edit->Project Settings->Input. In the example below I named them “Horizontal1”, “Horizontal2”, and so on.

// Set this 0-3 depending on which player the ball belongs to
[SerializeField]
int player = 0;

void FixedUpdate () 
{
    float moveHorizontal = 0;
    float moveVertical = 0;
   
    if (player == 0)
    {
        moveHorizontal = Input.GetAxis ("Horizontal1");
        moveVertical = Input.GetAxis ("Vertical1");
    } 
    else if (player == 1)
    {
        moveHorizontal = Input.GetAxis ("Horizontal2");
        moveVertical = Input.GetAxis ("Vertical2");
    } 
    else if (player == 2)
    {
        moveHorizontal = Input.GetAxis ("Horizontal3");
        moveVertical = Input.GetAxis ("Vertical3");
    } 
    else if (player == 3)
    {
        moveHorizontal = Input.GetAxis ("Horizontal4");
        moveVertical = Input.GetAxis ("Vertical4");
    }

    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

    rb.AddForce (movement * speed);
}

Also, on the forum you can use the [ code ] tags to put your code in so that it’s easier to read.

@Iron-Warrior
Thanks, so I can just use that code and all my 4 balls will be possible to roll at the same time?

Each player will control one individually and separately, yes.

@Iron-Warrior sorry im not really sure i understand it :confused: