※ 플레이어 점프 & 연속 점프 방지
public class PlayerController : MonoBehaviour {
private Rigidbody playerRb;
public float jumpForce = 10;
public float gravityModifier;
public bool isOnGround = true;
public bool gameOver = false;
void Start() {
playerRb = GetComponent<Rigidbody>();
Physics.gravity *= gravityModifier;
}
void Update() {
if (Input.GetKeyDown(KeyCode.Space) && isOnGround) {
playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isOnGround = false;
}
}
private void OnCollisionEnter(Collision collision) {
if (collision.gameObject.CompareTag("Ground"))
isOnGround = true;
else if (collision.gameObject.CompareTag("Obstacle")) {
Debug.Log("Game Over!!");
gameOver = true;
}
}
}
※ 장애물 자동으로 반복 생성
public class SpawnManager : MonoBehaviour
{
public GameObject obstaclePrefab;
private Vector3 spawnPos = new Vector3(25, 0, 0);
private float startDelay = 2;
private float repeatRate = 2;
private PlayerController playerControllerScript;
void Start()
{
InvokeRepeating("SpawnObstacle", startDelay, repeatRate);
playerControllerScript = GameObject.Find("Player").GetComponent<PlayerController>();
}
void SpawnObstacle()
{
if (playerControllerScript.gameOver == false)
Instantiate(obstaclePrefab, spawnPos, obstaclePrefab.transform.rotation);
}
}
※ 배경화면 반복 재생
public class RepeatBackground : MonoBehaviour
{
private Vector3 startPos;
private float repeatWidth;
void Start()
{
startPos = transform.position;
repeatWidth = GetComponent<BoxCollider>().size.x / 2;
}
void Update()
{
if (transform.position.x < startPos.x - repeatWidth)
transform.position = startPos;
}
}
※ 배경과 장애물 이동, 그리고 장애물 파괴
public class MoveLeft : MonoBehaviour
{
public float speed = 30;
private float leftBound = -15;
private PlayerController playerControllerScript;
void Start()
{
playerControllerScript = GameObject.Find("Player").GetComponent<PlayerController>();
}
void Update()
{
if (playerControllerScript.gameOver == false)
{
transform.Translate(Vector3.left * Time.deltaTime * speed);
}
if (transform.position.x < leftBound && gameObject.CompareTag("Obstacle"))
{
Destroy(gameObject);
}
}
}