70 lines
2.4 KiB
C#
70 lines
2.4 KiB
C#
using UnityEngine;
|
|
|
|
public class PlayerMove : MonoBehaviour
|
|
{
|
|
private RectTransform dinoRect;
|
|
private Canvas parentCanvas;
|
|
|
|
[Header("Pengaturan Gerak (UI)")]
|
|
public float speed = 15f;
|
|
public float batasKiri = -500f;
|
|
public float batasKanan = 500f;
|
|
|
|
void Start() {
|
|
// --- PERBAIKAN 1: Inisialisasi Komponen (WAJIB) ---
|
|
dinoRect = GetComponent<RectTransform>();
|
|
parentCanvas = GetComponentInParent<Canvas>();
|
|
|
|
// --- PERBAIKAN 2: Logic Ganti Skin yang Aman ---
|
|
int id = PlayerPrefs.GetInt("SkinDipakai", 0);
|
|
|
|
if (SkinData.instance != null) {
|
|
// Kita cari Image karena Dino kamu ada di UI (Canvas)
|
|
// Kalau Dino kamu pakai SpriteRenderer (World), pakai GetComponent<SpriteRenderer>()
|
|
UnityEngine.UI.Image imgDino = GetComponent<UnityEngine.UI.Image>();
|
|
|
|
if (imgDino != null && id < SkinData.instance.daftarSkin.Length) {
|
|
imgDino.sprite = SkinData.instance.daftarSkin[id].spriteGameplay;
|
|
}
|
|
}
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
// PENGAMAN: Jika dinoRect atau parentCanvas gagal ditemukan, jangan jalankan Update
|
|
if (dinoRect == null || parentCanvas == null) return;
|
|
|
|
if (Input.GetMouseButton(0))
|
|
{
|
|
Vector2 mousePos = Input.mousePosition;
|
|
Vector2 localMousePos;
|
|
|
|
// Baris 32 yang tadi error sekarang aman karena parentCanvas sudah di-assign di Start
|
|
RectTransformUtility.ScreenPointToLocalPointInRectangle(
|
|
parentCanvas.transform as RectTransform,
|
|
mousePos,
|
|
parentCanvas.worldCamera,
|
|
out localMousePos
|
|
);
|
|
|
|
float targetX = Mathf.Clamp(localMousePos.x, batasKiri, batasKanan);
|
|
Vector2 targetPosition = new Vector2(targetX, dinoRect.anchoredPosition.y);
|
|
|
|
dinoRect.anchoredPosition = Vector2.Lerp(dinoRect.anchoredPosition, targetPosition, Time.deltaTime * speed);
|
|
}
|
|
}
|
|
|
|
private void OnTriggerEnter2D(Collider2D collision)
|
|
{
|
|
if (collision.CompareTag("Sayur"))
|
|
{
|
|
GameManagerTangkap.instance.AddScore(10);
|
|
Destroy(collision.gameObject);
|
|
}
|
|
else if (collision.CompareTag("JunkFood"))
|
|
{
|
|
GameManagerTangkap.instance.TakeDamage();
|
|
Destroy(collision.gameObject);
|
|
}
|
|
}
|
|
} |