Magnetic
You know how Little Big Planet, Kingdom Hearts and similar have various pickups move towards your character when you get up close? Yea I also find that’s a nice bit of polish.
One way of getting that up and running in Unity is via the code below. Setup:
- Add all objects you want to get attracted to the player to a special layer.
- Attach the script below to your player.
- Set the layer mask on the component to include the layer from step one.
- Tweak, play, repeat.
Magnetic.cs:
public class Magnetic : MonoBehaviour
{
public LayerMask m_MagneticLayers;
public Vector3 m_Position;
public float m_Radius;
public float m_Force;
{
Collider[] colliders;
Rigidbody rigidbody;
colliders = Physics.OverlapSphere (transform.position + m_Position, m_Radius, m_MagneticLayers);
foreach (Collider collider in colliders)
{
rigidbody = (Rigidbody) collider.gameObject.GetComponent (typeof (Rigidbody));
if (rigidbody == null)
{
continue;
}
rigidbody.AddExplosionForce (m_Force * -1, transform.position + m_Position, m_Radius);
}
}
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere (transform.position + m_Position, m_Radius);
}
}
4 Comments
→
Neat, I’ll have to try that.
Thanks a lot!
Works like a charm!)))
Hey Thanks!
Its really nice thing. And fully works whats more
I’m making high-end (from art stand point) unity game and this script seems to be handy when polishing some game mechanics
Is it free for commercial use?
Anything from my tips and tricks section is public domain – unless otherwise specified. I would of-course appreciate a tip of the hat mentioning, but do whatever you want with it