So here’s what I’m trying to do:
You click on player one, and then control/move that player. You click on player two, then you control that and not control player one.
Here’s what is happening:
When I click on player one and move it, it moves. But when I leave the key and click on player two, player one still keeps moving.
Here’s a video that shows the problem:
I’ve created two scripts:
Movement script (which is on Player)
GameManager script (which is on game manager)
Here are the scripts:
Movement
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
float inputX;
Rigidbody2D rb;
[SerializeField] float jumpPower;
public Transform GroundCheck;
public LayerMask GroundLayer;
bool isGrounded;
private AudioSource audioSource;
public AudioClip jumpSound;
bool isSelected = false;
GameManager gameManager;
void Start()
{
Application.targetFrameRate = 60;
rb = GetComponent<Rigidbody2D>();
audioSource = GetComponent<AudioSource>();
gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
}
// Update is called once per frame
void Update()
{
if(isSelected)
{
inputX = Input.GetAxis("Horizontal");
if(Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A))
{
transform.rotation = Quaternion.Euler(0,180f,0);
}else if(Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D))
{
transform.rotation = Quaternion.Euler(0,0,0);
}
isGrounded = Physics2D.OverlapCapsule(GroundCheck.position,new Vector2(0.5f,0.3f),CapsuleDirection2D.Horizontal,0,GroundLayer);
if(Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.velocity = Vector2.up * jumpPower;
audioSource.PlayOneShot(jumpSound);
}
rb.velocity = new Vector2(inputX*200f*Time.deltaTime,rb.velocity.y);
}
}
private void FixedUpdate() {
}
public void DeselectPlayer()
{
isSelected = false;
}
private void OnMouseDown() {
gameManager.DeselectAllPlayers();
isSelected = true;
}
}
GameManager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public GameObject[] Players;
public void DeselectAllPlayers()
{
for(int i = 0;i<Players.Length;i++)
{
Players[i].GetComponent<Movement>().DeselectPlayer();
}
}
}