Random spawned objects affects other objects movement with collision

Viewed 22

I am trying the create a bubble like effect in unity. When any object lets say A is spawned to close to another object lets say B then the B object moves very fast and looses its bubbly/floaty effect. Is there any way to make all objects maintain a steady float state at every situation.

game

Here is the sphere code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sphere : MonoBehaviour
{
    Renderer sphereRenderer; 
    Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        sphereRenderer = GetComponent<Renderer>();    
        rb = GetComponent<Rigidbody>();
        SphereForce();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnCollisionEnter(Collision other)
    {
        if(other.gameObject.CompareTag("Sphere")){
            ChangeColor();
        }
    }

    void ChangeColor(){
        Color randColor = new Color(Random.Range(0.0f, 1f), Random.Range(0.0f, 1f), Random.Range(0.0f, 1f), 1.0f);
        if(sphereRenderer != null)
            sphereRenderer.material.SetColor("_Color", randColor);
    }

    void SphereForce(){
        rb.AddForce(new Vector3(Random.value, Random.value, Random.value) * Random.Range(20f, 30f), ForceMode.Force);
    }


}

Here is the spawn manager code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnManager : MonoBehaviour
{
    [SerializeField] private GameObject spherePrefb;

    List<GameObject> spawnedSpheres;

    private float minYPos = 0.2f;
    private float maxYPos = 8.2f;
    private float minXPos = -2.6f;
    private float maxXPos = 3.6f;
    private float minZPos = -2.6f;
    private float maxZPos = 3.6f;

    [SerializeField] private float startDelay;
    [SerializeField] private float repeatDelay;
    // Start is called before the first frame update
    void Start()
    {
        InvokeRepeating("SpawnSphere", startDelay, repeatDelay);
        spawnedSpheres = new List<GameObject>();
    }

    // Update is called once per frame
    void Update()
    {
    }

    void SpawnSphere(){
        if(spawnedSpheres.Count > 30){
            Destroy(spawnedSpheres[0]);
            spawnedSpheres.RemoveAt(0);
        }
        
        GameObject sphere = Instantiate(spherePrefb, new Vector3(Random.Range(minXPos, maxXPos), Random.Range(minYPos, maxYPos), Random.Range(minZPos, maxZPos)), Quaternion.identity);
        spawnedSpheres.Add(sphere);
    }
}

Note: Sphere has a Sphere Collider and a Rigidbody. The spheres are spawned inside an invisible box with collider to restrict sphere movement.

0 Answers
Related