Files
VR-GAME/Assets/Script/BallShooter.cs
2026-05-02 21:36:33 +07:00

63 lines
2.1 KiB
C#

using UnityEngine;
public class BallShooter : MonoBehaviour
{
public GameObject ballPrefab;
public Transform shootPoint;
[Header("Flick Sensitivity")]
[Tooltip("How much the swipe affects forward speed.")]
public float forwardSensitivity = 0.05f;
[Tooltip("How much the swipe affects upward loft.")]
public float upwardSensitivity = 0.02f;
[Tooltip("How much side-to-side swipe affects lateral direction.")]
public float lateralSensitivity = 0.03f;
[Header("Physics Tuning")]
[Tooltip("Minimum swipe velocity required to trigger a shot.")]
public float swipeThreshold = 100f;
[Tooltip("Maximum velocity allowed (prevents physics glitches).")]
public float maxVelocity = 1500f;
[Tooltip("Constant upward force added to every shot for a better arc.")]
public float baseUpwardBias = 2f;
public void FlickShoot(Vector2 swipeDelta, float swipeTime)
{
// Calculate velocity (pixels per second)
Vector2 swipeVelocity = swipeDelta / swipeTime;
float speed = swipeVelocity.magnitude;
// 1. Deadzone check: Ignore tiny accidental flicks
if (speed < swipeThreshold) return;
// 2. Clamp: Prevent extreme speeds
if (speed > maxVelocity)
{
swipeVelocity = swipeVelocity.normalized * maxVelocity;
}
GameObject newBall = Instantiate(ballPrefab, shootPoint.position, shootPoint.rotation);
Rigidbody rb = newBall.GetComponent<Rigidbody>();
// 3. Translate 2D swipe to 3D force
// swipeVelocity.y is vertical (up is positive)
// swipeVelocity.x is horizontal (right is positive)
float forwardForce = swipeVelocity.y * forwardSensitivity;
float upwardForce = (swipeVelocity.y * upwardSensitivity) + baseUpwardBias;
float lateralForce = swipeVelocity.x * lateralSensitivity;
Vector3 force = (shootPoint.forward * forwardForce) +
(Vector3.up * upwardForce) +
(shootPoint.right * lateralForce);
// Apply as Impulse for immediate movement
rb.AddForce(force, ForceMode.Impulse);
Destroy(newBall, 5f);
}
}