- Home /
,Start and Game over
Hi!
I am super new to Unity and trying to create my first project and I have no idea how to start or end the game at this point. The game has one character that is clickable/touchable, every click/touch generetes a point. As of right now when I press the "play" button in Unity the character falls from the middle of the screen down and then starts to bounce around, I've set it up this way with Rigidbody and box colliders.
I want to have the character frozen in place until i click/touch him, then he begins to fall. I also want to end the game whenever I click/touch the background, as in everything else except the character. When that happens I want the score saved and then just simply add a "Retry" button. Does that make any sense? Could someone point me in the right direction? :)
/Kim
Answer by Kciwsolb · Apr 18, 2018 at 08:57 PM
In your code, get a reference to the Rigidbody on the character in Awake. Then in Start call a function that enables the kinematic property of the rigidbody. A rigidbody marked as kinematic will not move except by code (read more here).
private Rigidbody rigidbody;
private void Awake()
{
rigidBody = GetComponent<Rigidbody>();
}
private void Start()
{
ResetGame();
}
public void ResetGame()
{
rigidbody.isKinematic = true; //Character is prevented from falling
}
public void StartGame()
{
rigidbody.isKinematic = false; //Character will start to fall
}
Now, you will need another script that gets the mouse position and checks for a hit on a collider when you click (there are plenty of examples of this so just do a quick search). Once you have that script, use the information from the collider hit to determine if what you clicked on was the player or not. If it was the player, do what ever you want. If it was anything else, call the public ResetGame method on the script above. That code will look something like this (again, this is not a complete script, I will leave that up to you. This is just to get you going in the right direction):
//Make sure you have a reference to the PlayerController or whatever you named the script above
private void HandleClick(Collider other) //Or what ever the mouse click script you find calls this function
{
if(other.gameObject.CompareTag("Player")) //Make sure player GameObject is tagged as "Player"
{
//Do whatever you want like adding to your score or adding a force to the player
}
else
{
playerController.ResetGame(); //Call ResetGame() on our reference to our first script
//Do other UI or score saving stuff
}
}
I suggest trying to narrow your question down to specific functionality in the future. It can be hard to answer otherwise. But I hope this helps get you going in the right direction! If this helps, please mark it as your answer! Good luck! :)