Magnetic

by AngryAnt on October 4th, 2009

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:

  1. Add all objects you want to get attracted to the player to a special layer.
  2. Attach the script below to your player.
  3. Set the layer mask on the component to include the layer from step one.
  4. Tweak, play, repeat.

 

Magnetic.cs:

using UnityEngine;
using System.Collections;

public class Magnetic : MonoBehaviour
{
    public LayerMask m_MagneticLayers;
    public Vector3 m_Position;
    public float m_Radius;
    public float m_Force;

    void FixedUpdate ()
    {
        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);
        }
    }

    void OnDrawGizmosSelected ()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere (transform.position + m_Position, m_Radius);
    }
}
4 Comments
  1. jre2 permalink

    Neat, I’ll have to try that.

  2. adamus888 permalink

    Thanks a lot!
    Works like a charm!)))

  3. Andrew permalink

    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? :D

  4. 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 ;)

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS

Spam protection by WP Captcha-Free