Unity - Tricky Particle Collisions - unity3d

I am making a prototype for my 2D game. It consists of a ball that launches missiles that are aimed to explode where the user clicks. The explosion of the missile releases particles, which hit the ball and exert a force on the ball. Here is a video.
I used a standard particle system with the Collision module activated. Then attached this script to the particle systems created be each explosion:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class particleInteraction : MonoBehaviour {
//PS Variables
ParticleSystem myPS;
public List<ParticleCollisionEvent> particleCollisions = new List<ParticleCollisionEvent>();
//Physics variables
public float effect;
// Use this for initialization
void Start () {
myPS = GetComponent<ParticleSystem>();
}
void OnParticleCollision (GameObject other)
{
//Checking if the hit object is indeed the ball
if (other.tag.Equals("Player"))
{
Rigidbody2D hitObject = other.GetComponent<Rigidbody2D>();
//Getting the number of particles hat hit the ball
int noOfCollisions = myPS.GetCollisionEvents(other, particleCollisions);
Vector3 particleDirection = new Vector2(0,0); //The overall velocity of all the particles that collided
//Iterating through all the collisions and adding their vectors
for (int i = 0; i < noOfCollisions; i++)
{
particleDirection += particleCollisions[i].velocity;
}
//Applying the resultant force
hitObject.AddForce(particleDirection.normalized * effect * noOfCollisions);
}
}
}
This mostly works, however it causes a problem. The missile are designed to explode when they hit the walls too, so when the ball is on a wall I expect a missile aimed at the wall to push the ball off of it. However, the ball simply jerks away from the wall in the next frame (can be seen in the video). I believe this is because of the colliders on the particles instantiating inside of the ball's collider. This causes the physics engine to immediately move the ball away in the next scene.
So I tried using OnParticleTrigger, however I realized that Unity doesn't provide info on the gameobject affected in particle triggers, so I cannot affect the ball.
Could anyone help me find a way to make this work? I want to avoid the jerky movement caused by the intersecting colliders, or maybe use a better method expressing the missile explosions.

reduce the Radius Scale under the Collision Tab.
you can visually debug this using visualize Bounds checked inside the module.

Related

Particle collision detection on cloned objects not working

I want to spawn several circles on the screen as game objects that float around randomly. To do this I have a prefab that I am instantiating x number of times in a script attached to a main game object. Then I have a 2nd script attached to the prefab to control the random movement. I added a Particle System to the prefab, so that each spawned clone has particles emitting from its edges. I want to know if one object's particles collide with anything, be it another cloned object, a wall, etc. But my OnParticleCollision (in the movement script attached to the prefab) is not logging anything to the console, it seems to not detect particle collisions at all. Maybe I'm not understanding the bigger concept and instantiating multiple instances of the same prefab with a particle system is not the best approach? Or am I making a more obvious minor mistake?
Things I have tried based on other questions:
Send collision messages IS checked
I do not have any colliders marked as triggers
I verified the visual bounds look correct in Scene View
Collision between cloned game objects themselves work fine, it's only the Particle Collisions not working.
My script attached to the prefab:
public class BubbleMove : MonoBehaviour
{
public Rigidbody2D rb;
void Start()
{
rb.velocity = new Vector2(min, max);
ParticleSystem ps = GetComponent<ParticleSystem>();
ps.transform.position = new Vector3(transform.position.x, transform.position.y, 0);
ps.Play();
}
// Update is called once per frame
void Update()
{
}
void OnParticleCollision(GameObject col){
Debug.Log("Collision Particle: " + col);
}
}
Images of my prefab inspector settings for Rigidbody2D, Circle Collider, and Particle System:
Hi I see the rigidbody is not defined in the inspector for the BubbleMove script.

How to detect a potential collision in Unity?

I have a Unity game I am working on as a hobby and have come across an interesting issue with how to best handle collision detection. My problem here is that my game is a 2D turn-based game, whereby a game object can move a fixed distance each time in a non-grid based world space. I have my game objects currently using BoxCollider2D to handle collision detection, but I need to be able to determine if there will be a collision BEFORE actually making a move, which right now causes the game object to overlap another game object and fire the OnCollisionEnter2D event. The eventual idea here is to allow a player to plan out a move and have a "navigation guide" appear next to the object to show move options based on the game object's move capabilities.
Is it possible to take my game object's collider, transform its position to move or rotate it, see if a collision would occur, but NOT actually move the object itself?
You mean like simply using Rigidbody.SweepTest ? ;)
Tests if a rigidbody would collide with anything, if it was moved through the Scene.
From the example
public class ExampleClass : MonoBehaviour
{
public float collisionCheckDistance;
public bool aboutToCollide;
public float distanceToCollision;
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
RaycastHit hit;
if (rb.SweepTest(transform.forward, out hit, collisionCheckDistance))
{
aboutToCollide = true;
distanceToCollision = hit.distance;
}
}
}
Oh just noted that actually this is only for 3D Rigidbody.
For 2D this doesn't exist but can be kind of replicated using instead Collider2D.Cast
Casts the Collider shape into the Scene starting at the Collider position ignoring the Collider itself.

How to keep the same velocity after bumping into things ? (Unity 2D)

My game (2D Top-Down view) is about a tank that fires bouncing bullets. Those bullets have infinite bounces and keep the same velocity after bouncing. It works fine with static objects, however it doesn't keep the same velocity with moving objects : the bullet can push things, but will slow and I don't know how to remove the slow.
Here is a tweet where you can see the bullets slow down after touching some objects :
https://twitter.com/TurboDevTeam/status/1350751139508215808?s=20
Edit :
Here are the parameters of the bullet :
derHugo's comment is on point: since the cars move when hit, they absorb part of the energy.
I've set up a minimal example to demonstrate.
The ball has a CircleCollider2D and a Rigidbody2D with Linear Drag = 0 and a material with Friction = 0 and Bounciness = 1.
The walls have a BoxCollider2D and a Rigidbody2D. Gravity is disabled.
For the first test, the wall Rigidbody2D is set to Static.
For the second test, the wall Rigidbody2D is set to Dynamic, with Mass = 10 and Linear Drag = 1.
In order to keep it bouncing forever in this case, you must code the bounciness by yourself. First remove the Physics Material or set the bounciness to 0, to make sure the Physics Engine is not simulating it.
Then, create a script for the bullet:
public class Bullet : MonoBehaviour
{
private Vector2 lastVelocity;
void FixedUpdate()
{
lastVelocity = GetComponent<Rigidbody2D>().velocity;
}
void OnCollisionEnter2D(Collision2D collision)
{
GetComponent<Rigidbody2D>().velocity = Vector2.Reflect(lastVelocity, collision.contacts[0].normal);
}
}
(Please note that you should use GetComponent carefully, maybe calling it only once on Start and saving a reference, I didn't do it to keep a minimal sample.)
The idea here is to take the velocity right before the collision and invert it. However, if you take the Rigidbody2D velocity on OnCollisionEnter, it's already the updated value. So you must store the value in FixedUpdate, since the next is only called after the OnCollisionEnter method.
Then, you use Vector2.Reflect to reflect the incoming velocity by the collision normal.
Vector2.Reflect results are valid in 2D:

Get Mesh of particle collider

How would I go about getting the mesh filter of a particle collision and than assign that mesh to the particle.
So I have a OnParticleCollision. I hit the object take this object I get its Mesh Filter. I than want to assign this to that of my particle so it takes the effect of its physical build.
Here is my code so far.
void Start()
{
Debug.Log("Script Starting...");
part = GetComponent<ParticleSystem>();
collisionEvents = new List<ParticleCollisionEvent>();
}
void OnParticleCollision(GameObject coll)
{
// Getting the object of the collider
Collider obj = coll.GetComponent<Collider>();
Mesh mesh = obj.GetComponent<MeshFilter>().mesh;
// Assign the mesh shape of the collider to that of the particle
ElectricWave.shape.meshRenderer = mesh; // I know this doesnt work as is.
// Play effect
ElectricWave.Play();
}
If you're wanting all particles in the system to take on that mesh, it's straightforward. Just get the collided-with object mesh and apply that to the ParticleSystemRenderer:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ParticleCollision : MonoBehaviour
{
private ParticleSystemRenderer particleRenderer;
void Start()
{
particleRenderer = GetComponent<ParticleSystemRenderer>();
}
void OnParticleCollision(GameObject other)
{
particleRenderer.renderMode = ParticleSystemRenderMode.Mesh;
particleRenderer.material = other.GetComponent<Renderer>().material;
}
}
However, if you instead are looking to change the mesh of only that particle, it will be a lot more complicated, since the ParticleCollisionEvent data does not contain which particle collided with it. A good starting point might be looking at the ParticleCollisionEvent.intersection value, and trying to find the particle nearest that point using GetParticles. It might be extrememly computationally expensive, though, if it works at all.
An easier way might be to fake it by having multiple particle systems with extremely low emission rates, so that changing the mesh of a whole particle system results in changing just one visible particle, and resetting the system's mesh before every new particle is emitted. That way you get the visual effect you're looking for, but under the hood it's multiple particle systems acting as one.

Unity - Inconsistant speed of object following raycast2D

So im creating a simple game and one component of the game is a greendot following the outside of the level. I got this working using a raycast in the middle which rotates and gives the position of collision the the gameobject.
game overview
The problem is that the speed is inconsistant at the moment since the distance between two collisions can be further distance if i have a slope. I also have the feeling that there should be a easier way to get the same result. What are your thoughts?
public class FollowPath : MonoBehaviour {
Vector3 collisionPos;
public GameObject greenDot;
void Update ()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up);
transform.Rotate(0.0f, 0.0f, 3);
if (hit.collider != null)
{
collisionPos = hit.point;
}
greenDot.transform.position = collisionPos;
}
}
I'm not sure if you will like this answer, as it suggests a complete departure from the way you were trying to do it.
A simple way to do this, would be to give your moving dot GameObject a Rigidbody2D component, AND a CircleCollider component.
Then, make your walls, and add to each an EdgeCollider component.
You'll probably also want to add a PhysicsMaterial2d to each GameObject with a Collider and set the friction and bounciness values for each.
Once this is setup, you can apply an initial force to the rigid body ball to get it moving, and it will bounce off the walls just like a ball does, using the Unity physics engine. No code would be needed in you update functions.