Kode #1 player movement
using UnityEngine;
public class Playermovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
// Update is called once per frame
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime );
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)
{
FindAnyObjectByType<GameManager>().EndGame();
}
}
}
Kode #2 Player collison
using System;
using UnityEngine;
public class PlayerColision : MonoBehaviour
{
public Playermovement movement;
void OnCollisionEnter(Collision collisionInfo)
{
if (collisionInfo.collider.tag == "obstacle")
{
movement.enabled = false;
FindAnyObjectByType<GameManager>().EndGame();
}
}
}
Kode #3 Endgame
using UnityEngine;
public class EndTrigger : MonoBehaviour
{
public GameManager gameManager;
void OnTriggerEnter()
{
gameManager.CompleteLevel();
}
}
Kode #4 Gamemanager
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
bool gameHasEnded = false;
public float restartDelay = 1f;
public GameObject completeLevelUI;
public void CompleteLevel()
{
completeLevelUI.SetActive(true);
}
public void EndGame()
{
if(gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("Game Over");
Invoke("Restart", restartDelay);
}
}
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}