feat: refactor BallShooter to support dynamic flick physics

This commit is contained in:
2026-05-02 21:26:42 +07:00
parent 80dd6f9dc3
commit 61467f78d2

View File

@@ -4,19 +4,39 @@ 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
// Gọi hàm này khi bấm nút Ném trên UI
public void ShootBall()
[Header("Flick Settings")]
public float forwardMultiplier = 0.05f;
public float arcMultiplier = 0.02f;
public float lateralMultiplier = 0.03f;
public float maxVelocity = 100f;
// Thay thế logic Ném cũ bằng logic Flick mới
public void FlickShoot(Vector2 swipeDelta, float swipeTime)
{
// Tính vận tốc (pixels trên giây)
Vector2 swipeVelocity = swipeDelta / swipeTime;
// Giới hạn để tránh "nổ" vật lý nếu flick quá nhanh
if (swipeVelocity.magnitude > maxVelocity)
{
swipeVelocity = swipeVelocity.normalized * maxVelocity;
}
GameObject newBall = Instantiate(ballPrefab, shootPoint.position, shootPoint.rotation);
Rigidbody rb = newBall.GetComponent<Rigidbody>();
// Thêm lực để quả bóng bay về phía trước và hơi hếch lên trên
rb.AddForce(shootPoint.forward * shootForce + Vector3.up * upwardForce);
// Chuyển đổi swipe 2D sang lực 3D
// Y swipe (lên/xuống) -> Tiến và Lên
// X swipe (trái/phải) -> Sang ngang
Vector3 force = (shootPoint.forward * swipeVelocity.y * forwardMultiplier) +
(Vector3.up * swipeVelocity.y * arcMultiplier) +
(shootPoint.right * swipeVelocity.x * lateralMultiplier);
// Hủy quả bóng sau 5 giây để tránh lag game
// Sử dụng Impulse để lực tác động tức thì
rb.AddForce(force, ForceMode.Impulse);
// Hủy quả bóng sau 5 giây
Destroy(newBall, 5f);
}
}