球體控制與碰撞
- 使用方向鍵輸入搭配 Rigidbody 推動球體。
- 並使用 OnTriggerEnter 碰撞事件做刪除&過關判斷。
在球體上增加 Rigidbody
- 點選球體,按下 Add Component
- 選擇 Physics / Rigidbody
在球體上增加 Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Ball : MonoBehaviour
{
public string nextScene;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 dir = new Vector3(h, 0, v);
Vector3 move = dir.normalized * 100 * Time.deltaTime;
rb.AddForce(move);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Coin")
{
other.gameObject.SetActive(false);
Destroy(other.gameObject);
GameObject[] objs = GameObject.FindGameObjectsWithTag("Coin");
if (objs.Length == 0)
{
SceneManager.LoadScene(nextScene);
}
}
}
}