Hallo, I am trying to create a PraticleSystem from scratch, I only want to use scripts.
I managed to spawn particles from a fixed position with random velocities and apply gravity and an external drag force to them. The particles work great.
Now I am trying to change their velocity ( create a custom collision with an invisible cube of edge size = 5) but I face a problem with local/global variables. The particle and rb are defined in the SpawnParticle() class. I want to use their velocity and position properties in the Update() class to check for collision each second.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PrefabSpawner : MonoBehaviour
{
public GameObject prefabParticle;
public Vector3 spawnPoint = Vector3.zero; // Set the spawn point at (0,0,0)
public float maxVelocity = 10f; // Set the maximum velocity in the Inspector
public Vector3 gravity = new Vector3(0, -9.81f, 0);
public float spawnRate = 10f; //set the spawnrate, make it public for inspector testing
private float timeSinceLastSpawn; //
public float lifetime = 5f; //destroy particles after some time to avoid memory deplition
public float forceDragCoef = 0.01f;
public GameObject particle;
public Rigidbody rb;
private void Start()
{
}
void Update()
{
timeSinceLastSpawn += Time.deltaTime;
if (timeSinceLastSpawn >= 1f/spawnRate)
{
timeSinceLastSpawn = 0f;
SpawnParticle();
if (particle.transform.position.x >= 5 || particle.transform.position.x <= 5)
{
rb.velocity.x = rb.veloctiy.x * (-1);
}
}
}
void SpawnParticle()
{
//create new particle
var particle = GameObject.Instantiate(prefabParticle);
var rb = particle.GetComponent<Rigidbody>();
if (rb == null)
{
rb = particle.AddComponent<Rigidbody>(); // this fixes an error occured as the particle clones appeared empty
}
//spawn position
particle.transform.position = spawnPoint;
//spawn with random veloctiy
particle.GetComponent<Rigidbody>().velocity = Random.insideUnitSphere * maxVelocity;
//add gravity
particle.GetComponent<Rigidbody>().AddForce(gravity, ForceMode.Acceleration);
//destroy particle after some time
Destroy(particle, lifetime);
// add custom force of f(drag) = -k*velocity
Vector3 forceDrag = -forceDragCoef * rb.velocity;
rb.AddForce(forceDrag, ForceMode.Force);
//add collision
//BoxCollider collider = gameObject.AddComponent<BoxCollider>();
particle.AddComponent<SphereCollider>();
particle.GetComponent<SphereCollider>().enabled = true;
}
}
I get the following error : the name ‘velocity’ does not exist in the current context
How can I make particle and rb objects available to be used in every class of the script ??
Thaanks !