Hello, I am making a game where the player has 2 forms you can switch between by pressing space. Initially changing to 2nd form works perfectly but changing back my input does not change the playerForm value for both children and I get frozen in air. The way I found to make this work at all was to use the forms as children of the player object and each child has the PlayerController script on it, but when in ball form I press space it changes the value in the script on ball form back to 1 and on the humanoid form it stays on 2. Default(humanoid) is value 1. At the end there there is a collision with ground that causes the same effect which also works fine, the problem is in the BallMovement method the space input only changes value for 1 child not both, what am I doing wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 5;
public float jumpSpeed = 2;
public float formChange = 1;
public float downSpeed = -5;
public float delayAmount = 0.2f;
[SerializeField] private int playerForm = 1;
bool onGround = true;
Vector2 moveVec;
Rigidbody2D rb;
public GameObject humanoidForm;
public GameObject paddle;
public GameObject ballForm;
// Start is called before the first frame update
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
moveVec = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (playerForm == 1)
{
PlayerMovement();
}
if (playerForm == 2)
{
BallMovement();
}
}
private void FixedUpdate()
{
}
void PlayerMovement()
{
rb.velocity = new Vector2(moveVec.x * speed, rb.velocity.y);
ballForm.transform.position = humanoidForm.transform.position;
paddle.transform.position = humanoidForm.transform.position;
if (Input.GetKey(KeyCode.UpArrow) && onGround)
{
onGround = false;
rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
}
if (Input.GetKey(KeyCode.Space))
{
playerForm = 2;
rb.velocity = new Vector2(rb.velocity.x, formChange);
ballForm.SetActive(true);
humanoidForm.SetActive(false);
Invoke(nameof(PaddleDelay), delayAmount);
}
}
void BallMovement()
{
humanoidForm.transform.position = ballForm.transform.position;
if (Input.GetKeyDown(KeyCode.Space))
{
playerForm = 1;
ballForm.SetActive(false);
humanoidForm.SetActive(true);
paddle.SetActive(false);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.collider.CompareTag("Ground"))
{
onGround = true;
if (playerForm == 2)
{
playerForm = 1;
humanoidForm.SetActive(true);
ballForm.SetActive(false);
paddle.SetActive(false);
}
}
if (collision.gameObject.tag == "Breakable" && playerForm == 2)
{
Destroy(collision.gameObject);
}
}
void PaddleDelay()
{
paddle.SetActive(true);
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider.CompareTag("Ground"))
{
onGround = false;
}
}
}