### Instantiate and Launch Projectile with Unity Input System Source: https://context7.com/giltcord/block-blasters/llms.txt Handles player input for launching projectiles, instantiating prefabs, and applying force. Requires a Rigidbody component on the prefab and uses Unity's new Input System for fire actions. It also requires a Transform for the starting position. ```csharp using UnityEngine; using UnityEngine.InputSystem; [RequireComponent(typeof(TrajectoryPredictor))] public class ProjectileThrow : MonoBehaviour { [SerializeField] Rigidbody objectToThrow; // Prefab to instantiate [SerializeField, Range(0.0f, 500.0f)] float force; // Launch force [SerializeField] Transform StartPosition; // Spawn point public InputAction fire; // Input binding // Usage in scene setup: // 1. Attach to cannon/launcher GameObject // 2. Assign projectile prefab to objectToThrow // 3. Set force value (e.g., 50-100 for typical gameplay) // 4. Configure fire InputAction (e.g., left mouse button) public void ThrowObject(InputAction.CallbackContext ctx) { if (objectToThrow != null && StartPosition != null) { Rigidbody thrownObject = Instantiate(objectToThrow, StartPosition.position, Quaternion.identity); thrownObject.AddForce(StartPosition.forward * force, ForceMode.Impulse); } } public void EnableInput() { fire.Enable(); fire.performed += ThrowObject; } public void DisableInput() { fire.performed -= ThrowObject; fire.Disable(); } } ``` -------------------------------- ### Mouse: First-Person Camera Controller with Smoothing in Unity Source: https://context7.com/giltcord/block-blasters/llms.txt The Mouse script implements a first-person mouse look controller for Unity. It allows for configurable sensitivity, vertical clamping, and input smoothing. The script locks and hides the cursor on start and can be configured to invert vertical rotation. ```csharp using UnityEngine; public class Mouse : MonoBehaviour { [Header("Rotation Settings")] public float horizontalSpeed = 2.0f; public float verticalSpeed = 2.0f; public bool invertVertical = false; [Header("Rotation Limits")] public bool clampVerticalRotation = true; public float minVerticalAngle = -80f; public float maxVerticalAngle = 80f; [Header("Smoothing")] public float rotationSmoothing = 5.0f; // Attach to camera or player pivot object // Cursor is locked and hidden on Start() // Press Escape to unlock cursor void Start() { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } void Update() { float mouseX = Input.GetAxis("Mouse X") * horizontalSpeed; float mouseY = Input.GetAxis("Mouse Y") * verticalSpeed * (invertVertical ? -1 : 1); currentRotation.y += mouseX; currentRotation.x -= mouseY; if (clampVerticalRotation) currentRotation.x = Mathf.Clamp(currentRotation.x, minVerticalAngle, maxVerticalAngle); transform.rotation = Quaternion.Euler(currentRotation); } } ``` -------------------------------- ### AudioManager: Manage Audio Playback (C#) Source: https://context7.com/giltcord/block-blasters/llms.txt A singleton audio controller responsible for managing background music and sound effects. It persists across scene loads using DontDestroyOnLoad and allows playing sound effects via a static instance. Setup involves creating an AudioManager GameObject with two AudioSources. ```csharp using UnityEngine; public class AudioManager : MonoBehaviour { public static AudioManager Instance; [SerializeField] AudioSource musicSource; [SerializeField] AudioSource sfxSource; public AudioClip BackgroundMusic; public AudioClip collectSound; public AudioClip shoot; public AudioClip LevelComplete; public AudioClip ButtonClick; // Play sound effects from any script: AudioManager.Instance.PlaySFX(AudioManager.Instance.collectSound); AudioManager.Instance.PlaySFX(AudioManager.Instance.LevelComplete); AudioManager.Instance.PlaySFX(AudioManager.Instance.ButtonClick); // Setup in scene: // 1. Create empty GameObject "AudioManager" // 2. Add two AudioSource components (music + sfx) // 3. Assign clips in Inspector // 4. Music auto-plays on Start() } ``` -------------------------------- ### TimerSystem: Manage Game Countdown and State Transitions in Unity Source: https://context7.com/giltcord/block-blasters/llms.txt The TimerSystem script manages the game's countdown timer, level completion, and transitions between game states and menus. It utilizes Unity's UI elements and DOTween for animated panel transitions. Dependencies include UnityEngine, SceneManagement, and DG.Tweening. ```csharp using UnityEngine; using UnityEngine.SceneManagement; using DG.Tweening; public class TimerSystem : MonoBehaviour { [Header("Timer Settings")] public float totalTime = 60f; // Countdown duration in seconds public TextMeshProUGUI timerText; // MM:SS display public Slider timerSlider; // Visual progress bar [Header("Menu Panel")] public GameObject menuPanel; public TextMeshProUGUI resultText; [Header("Buttons")] public Button retryButton; public Button mainMenuButton; public Button nextLevelButton; // Timer control methods: public void StartTimer(); // Begin countdown public void LevelCompleted(); // Trigger win state early // Navigation methods (assigned to buttons): public void RetryLevel() { Time.timeScale = 1f; SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } public void GoToMainMenu() { Time.timeScale = 1f; SceneManager.LoadScene("MainMenu"); } public void GoToNextLevel() { Time.timeScale = 1f; int nextIndex = SceneManager.GetActiveScene().buildIndex + 1; if (nextIndex < SceneManager.sceneCountInBuildSettings) SceneManager.LoadScene(nextIndex); else SceneManager.LoadScene("MainMenu"); } // Animated panel transitions using DOTween: public void PanelFadeIn(); // Slide up + fade in public void PanelFadeOut(); // Slide down + fade out } ``` -------------------------------- ### UI Animations: Panel Fade and Button Pop-in with DOTween in Unity Source: https://context7.com/giltcord/block-blasters/llms.txt This script provides DOTween-powered UI animation utilities for panel transitions and sequential button appearance effects. UIManager handles fading and positioning of UI panels, while ButtonAnimations animates a list of UI elements to pop in sequentially. ```csharp using UnityEngine; using DG.Tweening; using System.Collections; using System.Collections.Generic; // Panel fade animations public class UIManager : MonoBehaviour { public float fadetime = 1f; public CanvasGroup canvasGroup; public RectTransform rectTransform; public void PanelFadeIn() { canvasGroup.alpha = 0f; rectTransform.localPosition = new Vector3(0f, -100f, 0f); rectTransform.DOAnchorPos(Vector2.zero, fadetime).SetEase(Ease.OutElastic); canvasGroup.DOFade(1f, fadetime); } public void PanelFadeOut() { rectTransform.DOAnchorPos(new Vector2(0f, -100f), fadetime).SetEase(Ease.InOutQuint); canvasGroup.DOFade(0f, fadetime); } } // Sequential button pop-in animation public class ButtonAnimations : MonoBehaviour { public List items = new List(); public float fadetime = 1f; IEnumerator ItemsAnimation() { foreach (var item in items) item.transform.localScale = Vector3.zero; foreach (var item in items) { item.transform.DOScale(1f, fadetime).SetEase(Ease.OutBounce); yield return new WaitForSeconds(0.25f); } } } ``` -------------------------------- ### Import DOTween Namespace in C# Source: https://github.com/giltcord/block-blasters/blob/main/Assets/Plugins/Demigiant/DOTween/readme.txt To use DOTween functionalities in your C# scripts within Unity, you need to import the 'DG.Tweening' namespace. This allows direct access to DOTween's classes and methods for creating tweens. ```csharp using DG.Tweening; public class MyScript : MonoBehaviour { void Start() { // Your DOTween code here } } ``` -------------------------------- ### Visualize Projectile Trajectory with LineRenderer and Raycasting Source: https://context7.com/giltcord/block-blasters/llms.txt Visualizes the predicted path of a projectile using a LineRenderer and a hit marker. It calculates the physics-based trajectory, accounting for gravity and drag, and uses raycasting to detect the impact point. Requires a LineRenderer component and a Transform for the hit marker. ```csharp using UnityEngine; [RequireComponent(typeof(LineRenderer))] public class TrajectoryPredictor : MonoBehaviour { [SerializeField] Transform hitMarker; // Impact point indicator [SerializeField, Range(10, 100)] int maxPoints = 50; // Line resolution [SerializeField, Range(0.01f, 0.5f)] float increment = 0.025f; // Time step [SerializeField, Range(1.05f, 2f)] float rayOverlap = 1.1f; // Raycast multiplier // Called every frame by ProjectileThrow public void PredictTrajectory(ProjectileProperties projectile) { Vector3 velocity = projectile.direction * (projectile.initialSpeed / projectile.mass); Vector3 position = projectile.initialPosition; for (int i = 1; i < maxPoints; i++) { // Apply gravity and drag velocity += Physics.gravity * increment; velocity *= Mathf.Clamp01(1f - projectile.drag * increment); Vector3 nextPosition = position + velocity * increment; // Check for collision along trajectory if (Physics.Raycast(position, velocity.normalized, out RaycastHit hit, Vector3.Distance(position, nextPosition) * rayOverlap)) { // Found impact point - update line and marker trajectoryLine.SetPosition(i - 1, hit.point); break; } position = nextPosition; } } public void SetTrajectoryVisible(bool visible) { trajectoryLine.enabled = visible; hitMarker.gameObject.SetActive(visible); } } ``` -------------------------------- ### PlayerStats: Track and Persist Player Statistics (C#) Source: https://context7.com/giltcord/block-blasters/llms.txt Manages player statistics like collisions and level completion, persisting data using PlayerPrefs. It provides methods to add collisions, mark levels as complete, save/load progress, and reset stats. Access is through a static singleton instance. ```csharp using UnityEngine; using System.Collections.Generic; public class PlayerStats : MonoBehaviour { public static PlayerStats Instance { get; } // Singleton access // Access stats from any script: int total = PlayerStats.Instance.GetTotalCollisions(); int currentLevel = PlayerStats.Instance.GetCurrentLevelCollisions(); int levelsCompleted = PlayerStats.Instance.GetCompletedLevels(); Dictionary perLevel = PlayerStats.Instance.GetLevelCollisions(); // Record a collision (typically called from CollisionTally) PlayerStats.Instance.AddCollision(); // Auto-detects current scene name PlayerStats.Instance.AddCollision("Level_03"); // Explicit level name // Mark level as complete (called by TimerSystem on success) PlayerStats.Instance.LevelCompleted(); // Data persistence (automatic on level load) PlayerStats.Instance.SaveStats(); PlayerStats.Instance.LoadStats(); // Reset all progress PlayerStats.Instance.ResetAllStats(); // Get formatted string for UI display string stats = PlayerStats.Instance.GetFormattedStats(); // Output: "Player Statistics:\nTotal Collisions: 47\nLevels Completed: 3\nCurrent Level Collisions: 12" } ``` -------------------------------- ### Define Projectile Physics Properties with a Struct Source: https://context7.com/giltcord/block-blasters/llms.txt Encapsulates all physics parameters required for trajectory calculation and projectile behavior into a single struct. This includes direction, initial position, speed, mass, and drag. It simplifies passing physics data between components. ```csharp using UnityEngine; public struct ProjectileProperties { public Vector3 direction; // Launch direction (normalized) public Vector3 initialPosition; // Spawn world position public float initialSpeed; // Force magnitude public float mass; // Rigidbody mass public float drag; // Linear damping } // Usage example: ProjectileProperties props = new ProjectileProperties { direction = transform.forward, initialPosition = spawnPoint.position, initialSpeed = 75f, mass = 1f, drag = 0.1f }; trajectoryPredictor.PredictTrajectory(props); ``` -------------------------------- ### CollisionTally: Detect and Count Collisions (C#) Source: https://context7.com/giltcord/block-blasters/llms.txt A Unity component that detects and counts collisions on game objects. It integrates with PlayerStats for global tracking, supports tag-based filtering, and includes a cooldown mechanism to prevent duplicate counts. It can also update a UI TextMeshProUGUI element. ```csharp using UnityEngine; using TMPro; public class CollisionTally : MonoBehaviour { [Header("Tally Settings")] public int collisionCount = 0; public string targetTag = "Block"; // Only count collisions with this tag public bool useTagFilter = true; [Header("UI Settings")] public TextMeshProUGUI tallyText; public string displayPrefix = "Collisions: "; [Header("Collision Cooldown")] public bool useCooldown = true; public float cooldownTime = 0.5f; // Prevent rapid duplicate counts // Attach to projectile prefab: // 1. Add Rigidbody component (required) // 2. Tag target blocks as "Block" // 3. Optionally assign UI text for local display private void OnCollisionEnter(Collision collision) { // Cooldown check if (useCooldown && Time.time < lastCollisionTime + cooldownTime) return; // Tag filter if (useTagFilter && !collision.gameObject.CompareTag(targetTag)) return; collisionCount++; PlayerStats.Instance.AddCollision(); // Global tracking UpdateTallyDisplay(); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.