'Unity Take and Throw Ball
I'm try to make Basketball hoops, I can throw ball one time, I reset game but I can not throw ball again , I don't like to reset scene.
GameController
is a empty object [Manager] and below script attach to it.
GameController.cs:
public PlayerArcade player;
public float restartTime = 5f;
public static bool ResetBall = false;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
if(player.HoldingBall == false)
{
restartTime -= Time.deltaTime;
if (restartTime <= 0)
{
//SceneManager.LoadScene("Intro");
ResetBall = true;
restartTime = 5f;
}
// ResetBall = true;
}
}
My main player script as PlayerArcade.cs:
public GameObject Ball;
public Ball ball;
Rigidbody ballrb;
public GameObject PlayerCamera;
public float BallDistance = 1f;
public float ThrowPowerStrong = 550f;
public float ThrowPowerWeak = 350f;
public bool HoldingBall = true;
void Start()
{
ballrb = Ball.GetComponent<Rigidbody>();
ballrb.useGravity = false;
}
private void Awake()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
if (GameController.ResetBall == true)
{
ballrb.constraints = RigidbodyConstraints.None;
Ball.transform.position = new Vector3(212.5f, 3.227f, 4.11f);
ballrb.velocity = Vector3.zero;
ballrb.angularVelocity = Vector3.zero;
ballrb.transform.eulerAngles = new Vector3(0f, 0f, 0f);
ballrb.useGravity = false;
HoldingBall = true;
}
if (HoldingBall)
{
Ball.transform.position = PlayerCamera.transform.position + PlayerCamera.transform.forward * BallDistance;
if (Input.GetKeyDown(KeyCode.Y))
{
Debug.Log(ThrowPowerStrong);
HoldingBall = false;
ballrb.useGravity = true;
ballrb.AddForce(PlayerCamera.transform.forward * ThrowPowerStrong);
}
if (Input.GetKeyUp(KeyCode.A))
{
HoldingBall = false;
ballrb.useGravity = true;
ballrb.AddForce(PlayerCamera.transform.forward * ThrowPowerWeak);
}
}
}
And Ball.cs is attached to my ball object:
public PlayerArcade player;
[SerializeField] Transform PlayerBall;
Rigidbody ballrb;
// Start is called before the first frame update
void Start()
{
ballrb = PlayerBall.GetComponent<Rigidbody>();
}
private void Awake()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
Solution 1:[1]
when you throw the ball by pressing (A, or Y) just do
GameController.ResetBall = false; GameController.ResetBall = false;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | planetcreate |