Advertisement
afenkurtz

Sonic Pachinko Main Logic

Jan 29th, 2024
1,247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 KB | Gaming | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Managers : MonoBehaviour
  6. {
  7.     [SerializeField] GameObject sonicPrefab;
  8.     [SerializeField] Transform spawnPoint;
  9.     [SerializeField] Transform targetMaxDistance;
  10.     [SerializeField] float speed = 5.0f;
  11.     [SerializeField] float spawnDelay = 0.5f;
  12.  
  13.     private GameObject sonicInstance;
  14.     private Rigidbody2D sonicRB;
  15.     private Vector3 targetPosition;
  16.    
  17.     private bool attemptInProgress;
  18.  
  19.     private void Start()
  20.     {
  21.         // spawn sonic clone
  22.         Debug.Log("Creating first sonic");
  23.         sonicInstance = Instantiate(sonicPrefab, spawnPoint.position, spawnPoint.rotation);
  24.         // freeze constraints
  25.         sonicRB = sonicInstance.GetComponent<Rigidbody2D>();
  26.         sonicRB.constraints = RigidbodyConstraints2D.FreezeAll;
  27.         attemptInProgress = false;
  28.         targetPosition = targetMaxDistance.position;
  29.     }
  30.  
  31.     private void FixedUpdate()
  32.     {
  33.         if (Input.GetKey(KeyCode.Mouse0) && !attemptInProgress)
  34.         {
  35.             Debug.Log("Starting attempt");
  36.             attemptInProgress = true;
  37.             sonicRB.constraints = RigidbodyConstraints2D.None;
  38.         }
  39.  
  40.         if (!attemptInProgress)
  41.         {
  42.             var step = speed * Time.deltaTime;
  43.             sonicInstance.transform.position = Vector3.MoveTowards(sonicInstance.transform.position, targetPosition, step);
  44.  
  45.             if (Vector3.Distance(sonicInstance.transform.position, targetPosition) < 0.001f)
  46.             {
  47.                 // flip position to neg
  48.                 targetPosition.x *= -1.0f;
  49.             }
  50.         }
  51.     }
  52.  
  53.     private IEnumerator SpawnSonic()
  54.     {
  55.         yield return new WaitForSeconds(spawnDelay);
  56.         Debug.Log("Creating new sonic");
  57.         sonicInstance = Instantiate(sonicPrefab, spawnPoint.position, spawnPoint.rotation);
  58.         sonicRB = sonicInstance.GetComponent<Rigidbody2D>();
  59.         sonicRB.constraints = RigidbodyConstraints2D.FreezeAll;
  60.         attemptInProgress = false;
  61.         targetPosition.x *= -1.0f;
  62.     }
  63.  
  64.     public void ResetSonic()
  65.     {
  66.         Debug.Log("Killing sonic");
  67.         Destroy(sonicInstance);
  68.         StartCoroutine(SpawnSonic());
  69.     }
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement