Reputation: 13
I'm trying to create a platformer game that has two playable characters. When the user clicks on the right side of the screen, the first character jumps and when the left side of the screen is clicked, the other character jumps.
I have been able to get the first player to jump but not able to get the second one to jump.
if (Input.GetMouseButtonDown(0) && !IsDead)
{
jump = true;
}
This code works for one character but I'm unable to make the second character to jump.
EDIT
@derHugo , thanks for the reply. I tried implementing the code that you provided. It works for player 2 but player 1 is not working as expected. Here's what I have:
public enum WhichPlayer
{
Player1,
Player2
};
public WhichPlayer whichPlayer;
void Update () {
if (Input.GetMouseButtonDown(0) && !IsDead){
Vector2 position = Input.mousePosition;
bool leftHalf = position.x <= Screen.width / 2;
if (whichPlayer == WhichPlayer.Player1 && !leftHalf || whichPlayer == WhichPlayer.Player2 && leftHalf)
{
jump = true;
animator.SetBool("Jump", true);
} else {
jump = false;
animator.SetBool("Jump", false);
}
Player 2: When the left side of the screen is clicked, player 2 jumps and the animation plays. When the right side of the screen is clicked, player 2 stays on the ground and the animation doesn't play.
Player 1: When the right side of the screen is clicked, player 1 jumps and the animation plays. When the left side of the screen is clicked, player 1 still jumps but the animation doesn't play. I'm not able to figure out why player 1 still jumps because the animation stops and that's because of the code in the "else" block.
Upvotes: 0
Views: 519
Reputation: 90872
I don't see the check for deciding
When the user clicks on the right side of the screen, the first character jumps and when the left side of the screen is clicked, the other character jumps.
This requires two things:
The "Player" needs two know whether it is Player1 or Player2
You could use e.g. an enum for that like
public enum WhichPlayer
{
Player1,
Player2
}
and in your Player script add it as a field
public WhichPlayer whichPlayer;
and set it in the Inspector.
You need to check whether you clicked on right or left part of the screen
if (Input.GetMouseButtonDown(0) && !IsDead)
{
// get mouse position
var position = Input.mousePosition;
// get left or right half of screen
// it is left if the mouseposition x
// is smaller then the center of the screen
var leftHalf = position.x <= Screen.width / 2;
// finally check player type and screen side
if(whichPlayer == Player1 && leftHalf || whichPlayer == Player2 && !leftHalf)
{
jump = true;
}
}
(see Screen.width
and Input.mousePosition
both come in pixels)
Upvotes: 0