56 lines
2.1 KiB
C#
56 lines
2.1 KiB
C#
using UnityEngine;
|
|
|
|
public class BallShooter : MonoBehaviour
|
|
{
|
|
public GameObject ballPrefab; // Kéo prefab quả bóng vào đây
|
|
public Transform shootPoint; // Kéo điểm ShootPoint vào đây
|
|
public float shootForce = 500f;
|
|
public float upwardForce = 200f; // Lực ném vòng cung lên trên
|
|
|
|
[Header("Shooting Limit")]
|
|
public float shootCooldown = 2f; // Thời gian chờ giữa 2 lần ném
|
|
private float nextShootTime = 0f;
|
|
|
|
public void ShootBall()
|
|
{
|
|
// Kiểm tra xem đã đến lúc được ném chưa
|
|
if (Time.time < nextShootTime)
|
|
{
|
|
Debug.Log($"<color=yellow>Chờ một chút! Cần {(nextShootTime - Time.time):F1}s nữa để ném tiếp.</color>");
|
|
return;
|
|
}
|
|
|
|
// Cập nhật thời gian ném tiếp theo
|
|
nextShootTime = Time.time + shootCooldown;
|
|
|
|
// 1. Lấy vị trí ném: Từ Camera lùi xuống dưới một chút (giống tay người cầm bóng)
|
|
Vector3 spawnPosition = Camera.main.transform.position
|
|
+ Camera.main.transform.forward * 0.5f
|
|
- Camera.main.transform.up * 0.2f;
|
|
|
|
// 2. Tạo quả bóng
|
|
GameObject newBall = Instantiate(ballPrefab, spawnPosition, Camera.main.transform.rotation);
|
|
|
|
// 3. Đảm bảo bóng không bị dính vào Image Target
|
|
newBall.transform.SetParent(null);
|
|
|
|
// Gán vị trí ném vào script BouncyBall
|
|
BouncyBall ballScript = newBall.GetComponent<BouncyBall>();
|
|
if (ballScript != null)
|
|
{
|
|
ballScript.shotPosition = Camera.main.transform.position;
|
|
}
|
|
|
|
Rigidbody rb = newBall.GetComponent<Rigidbody>();
|
|
if (rb != null)
|
|
{
|
|
// 4. Lấy hướng nhìn của điện thoại
|
|
Vector3 shootDirection = Camera.main.transform.forward;
|
|
|
|
// 5. Thêm lực ném (Mạnh hơn một chút để bay tới rổ trên bàn)
|
|
rb.AddForce(shootDirection * shootForce + Vector3.up * upwardForce);
|
|
}
|
|
|
|
Destroy(newBall, 5f);
|
|
}
|
|
} |