Reputation: 13
I made a game following a YouTube tutorial https://www.youtube.com/playlist?list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6 I am on episode 8 and when I start the game the end game text comes up and I assume it is because the player touches the ground I cannot see any difference between the coding that I have produced and the YouTuber
GAME MANAGER: using UnityEngine;
public class GameManager : MonoBehaviour
{
bool gameHasEnded = false;
// Start is called before the first frame update
public void EndGame ()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("GAME OVER");
}
}
}
PLAYER COLLISIONS: using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
public PlayerMovement movement;
void OnCollisionEnter (Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Block")
{
movement.enabled = false;
} FindObjectOfType<GameManager>().EndGame();
}
}
PLAYER MOVEMENT:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{ //to substitute rigidbody to rb
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
// Update is called once per frame
void FixedUpdate()
{
//add forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
//only exectued if condition is met
if ( Input.GetKey("d") )
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0,
ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0,
ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
Upvotes: 0
Views: 102
Reputation: 889
The problem is here:
void OnCollisionEnter (Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Block")
{
movement.enabled = false;
} FindObjectOfType<GameManager>().EndGame();// <--- It is outside the if
}
Should be like this:
void OnCollisionEnter (Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Block")
{
movement.enabled = false;
FindObjectOfType<GameManager>().EndGame();
}
}
It ended the game whenever you collided with something, instead of doing it when it is a block only.
Upvotes: 3