- Home /
Set Player 2 to use player 1's postion in world
Hey Guys
What I'm trying to do is, using this rather messy code, when I press say 2, to switch from Character 1 to Character 2, I want Player 2 to have the same Position as Player 1, I've tried several methods so far but nothing seems to be working correctly.
This is the code I have running so far (I'm sure my way of turning on and off Characters is a terrible way, but for the moment it works until I can think of a more elegant and smart solution).
I'd appreciate any help or tips you can provide, I'm sure its a small thing but It's just not getting there. Thanks guys.
var currentPlayer : int = 1;
var C1 : GameObject;
var C2 : GameObject;
var C3 : GameObject;
function Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1) && currentPlayer != 1 ){
print("1 pressed");
C1.SetActive(true);
C2.SetActive(false);
C3.SetActive(false);
}
if (Input.GetKeyDown(KeyCode.Alpha2) && currentPlayer != 2 ){
print("2 pressed");
C1.SetActive(false);
C2.SetActive(true);
C3.SetActive(false);
}
if (Input.GetKeyDown(KeyCode.Alpha3) && currentPlayer != 3 ){
print("3 pressed");
C1.SetActive(false);
C2.SetActive(false);
C3.SetActive(true);
}
}
Answer by aldonaletto · Jun 02, 2013 at 02:40 AM
If you want to move the newly selected character to the current character position, it would be better to store the characters in an array - this would also reduce a lot your code:
var currentPlayer : int = 0; // player numbers start at 0 now
var players: GameObject[]; // set the size and assign the players in the Inspector
function Update()
{
var selPlayer = currentPlayer; // assume no change
// verify if a new player is being selected:
if (Input.GetKeyDown(KeyCode.Alpha1)) selPlayer = 0;
if (Input.GetKeyDown(KeyCode.Alpha2)) selPlayer = 1;
if (Input.GetKeyDown(KeyCode.Alpha3)) selPlayer = 2;
if (selPlayer != currentPlayer){ // if player changed...
players[selPlayer].SetActive(true); // activate new player
// move new player to current position:
players[selPlayer].transform.position = players[currentPlayer].transform.position;
players[currentPlayer].SetActive(false); // deactivate old player
currentPlayer = selPlayer; // update variable currentPlayer
}
}
Oh Wow great thanks, you answered my question and fixed my code too, couldn't have asked for a better answer, thankyou so much.