Hi all,
I’m completely new to coding and I’m trying to get a simple two-player turn-based top-down game going where two players share one keyboard.
Player 1 is currently mapped to the arrow keys and player 2 to the WASD keys. I’d like for each player to be able to move one space at a time in turns.
My code so far (below) seems to be allowing one player to move rather than the other and I’m stuck on the logic. Any help would be super appreciated!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TurnBased : MonoBehaviour
{
private enum State { Player1Move, Player2Move, GameOver }
private State state;
public GameObject player1;
public GameObject player2;
int x;
// Start is called before the first frame update
void Start()
{
state = State.Player1Move;
player1 = GameObject.FindGameObjectWithTag("Player");
player2 = GameObject.FindGameObjectWithTag("Player2");
}
// Update is called once per frame
void Update()
{
int x = 0;
if (Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow))
{
x++;
}
else if (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.W))
{
x--;
}
if(x == 0)
{
state = State.Player1Move;
}
else if (x == 1)
{
state = State.Player2Move;
}
switch (state)
{
case State.Player1Move:
player1.GetComponent<Player1Movement>().enabled = true;
player2.GetComponent<Player2Movement>().enabled = false;
break;
case State.Player2Move:
player1.GetComponent<Player1Movement>().enabled = false;
player2.GetComponent<Player2Movement>().enabled = true;
break;
}
}
}
Thanks!