I have a 2D platformer. In it, there’s a weapon that freezes things for a fixed amount of time, so it changes the friction properties for everything close by. The problem is, I have items far away from it that are also being affected because they share the same sharedMaterial. I have read that this is not a problem with the 3D equivalent “Collider” and “material”, but I need to stick to “Collider2D”, and I would rather not make/reference 1000 distinct sharedMaterials. Thoughts? I appreciate any ideas.
Thank you for the clarifying question.
I want the friction to be a function of distance from the point of contact and starting friction. So imagine the freeze weapon hits a spot at (0,0), there’s an item A at (0,1) and another item B with the same sharedMaterial at (0,2). I want A to be more slippery than B for like 5 seconds, and then return to normal.
Any new thoughts now? It’s kinda tricky.
First post here on the forums too, so please give me a virtual slap if I’m doing something out of the forum’s social canon.
sharedMaterial is just that, it’s a material shared by many objects (all instances of the same prefab by default use the same material). Changing it would change all those objects.
In 3d, you have a material
property, for some reason they didn’t put it in 2d. But it is simple to simulate the same behaviour. What happens is when you access collider.material, it creates a new material, a copy of the sharedMaterial, attaches it to the collider, and then returns it. So in your script, you could use these lines to do just that (Haven’t tried it myself though):
PhysicsMaterial2D newMaterial = Instantiate(collider2d.sharedMaterial);
collider2d.sharedMaterial = newMaterial;
now whatever you change in the sharedMaterial will only affect this one.
BUT - this way you might create many 1000 physics materials like you said. So what you have to do, is to create a cache for all those materials that have the same properties. use this code:
collider2d.sharedMaterial = GetMaterial(friction); // friction is the amount of friction you calculated that is required
private static Dictionary<float, PhysicsMaterial2D> materialCache = new Dictionary<float, PhysicsMaterial2D>();
private static PhysicsMaterial2D GetMaterial(float friction) {
if (!materialCache.ContainsKey(friction)) {
materialsCache[friction] = Instantiate(collider2d.sharedMaterial);
materialsCache[friction].friction = friction;
}
return materialsCache[friction];
}
This will only create one material per friction, and reuse it to all objects that require that kind of friction.
Note: you might want to clear the cache when necessary or use a smarter cache, since I used static and it never clears.