Files
VR-GAME/Assets/Script/BallShooter.cs
2026-05-12 01:22:46 +07:00

77 lines
2.5 KiB
C#

using UnityEngine;
public class BallShooter : MonoBehaviour
{
public GameObject ballPrefab;
public Transform shootPoint;
public float shootForce = 500f;
public float upwardForce = 200f;
[Header("Audio")]
public System.Collections.Generic.List<AudioClip> shootSounds;
[Header("Shooting Limit")]
public float shootCooldown = 1f;
private float nextShootTime = 0f;
public void ShootBall()
{
PerformShoot(Camera.main.transform.forward, shootForce, upwardForce);
}
public void FlickShoot(Vector2 swipeDelta, float swipeTime)
{
if (swipeDelta.y <= 0) return;
float speed = (swipeDelta.y / Screen.height) / Mathf.Max(swipeTime, 0.05f);
float forceMultiplier = Mathf.Clamp(speed * 1.5f, 0.6f, 2.5f);
float horizontalShift = (swipeDelta.x / Screen.width) * 1.5f;
Vector3 shootDirection = Camera.main.transform.forward + Camera.main.transform.right * horizontalShift;
shootDirection.Normalize();
float finalForce = shootForce * forceMultiplier;
float finalUpForce = upwardForce * (forceMultiplier * 0.8f);
PerformShoot(shootDirection, finalForce, finalUpForce);
#if UNITY_ANDROID || UNITY_IOS
Handheld.Vibrate();
#endif
}
private void PerformShoot(Vector3 direction, float force, float upForce)
{
if (Time.time < nextShootTime) return;
nextShootTime = Time.time + shootCooldown;
// Lấy ngẫu nhiên 1 trong các âm thanh ném
if (AudioPool.Instance != null && shootSounds != null && shootSounds.Count > 0)
{
AudioClip randomClip = shootSounds[Random.Range(0, shootSounds.Count)];
AudioPool.Instance.PlaySound(randomClip, 0.8f, true);
}
Vector3 spawnPosition = Camera.main.transform.position
+ Camera.main.transform.forward * 0.5f
- Camera.main.transform.up * 0.2f;
GameObject newBall = Instantiate(ballPrefab, spawnPosition, Camera.main.transform.rotation);
newBall.transform.SetParent(null);
BouncyBall ballScript = newBall.GetComponent<BouncyBall>();
if (ballScript != null)
{
ballScript.shotPosition = Camera.main.transform.position;
}
Rigidbody rb = newBall.GetComponent<Rigidbody>();
if (rb != null)
{
rb.AddForce(direction * force + Vector3.up * upForce);
}
Destroy(newBall, 5f);
}
}