Unity 2D how to create a magnet January 1, 2017 / , ,

Make your coin a Rigidbody and try velocit to the coin.  The idea is that you have a trigger circle around the coin.

Also change the tag of the magnet gameobject to “magnet”.

Then set the code inside the class of coin you want pulled in.

bool inside;
public Transform magnet;
private CircleCollider2D circleCollider;
void Start ()
{
circleCollider = transform.GetComponent<CircleCollider2D> ();
circleCollider.radius = 5f;
}

// Update is called once per frame
void Update ()
{

}

public void FixedUpdate ()
{

if(inside){ //when inside the Magnet apply magnet’s forces
Vector2 direction = (transform.position – magnet.position).normalized; //find the direction to move
float travelSpeed = Vector2.Distance(transform.position, magnet.position); //set the speed of the score bubble to the distance between it and the player

GetComponent<Rigidbody2D>().velocity = -direction * travelSpeed*20; //set velocity instead of apply force to avoid orbiting scenarios
}
}
void OnTriggerEnter2D(Collider2D other){
if(other.gameObject.tag ==”magnet”){
inside =true;
}
}
void OnTriggerExit2D(Collider2D other){
if (other.gameObject.tag == “magnet”) {
inside = false;
}
}

 

Inspiration:https://www.reddit.com/r/Unity2D/comments/2cnwiq/2d_magnet_best_practice_xpost_from_runity3d/