Magnet Effect[2D]

First of all this is a 2D game.

Hello, I made a item what give at the player a bonus"effect" to attracting items to him, like attract apples,etc… here is the code :

	//Here the magnet effect.
	private Vector3 character;
	private Vector2 characterdirection;
	private float Xdif;
	private float Ydif;
	private float speed;
	public static bool Iman = false;
	public GameObject ImanEfecto;
	

	void Start () {
		speed = 15;
	
	}
	
	// Update is called once per frame
	void Update () {
		try {
		if (Iman) {
						character= GameObject.FindGameObjectWithTag ("Player").transform.position;
						Xdif = character.x - transform.position.x;
						Ydif = character.y - transform.position.y;
						characterdirection= new Vector2 (Xdif, Ydif);
						rigidbody2D.AddForce (characterdirection.normalized * speed);
				}
		} catch {

				}

	
	}

This code works … but not very well, for example if the character jumps or makes a strong move, items go away above or below character position

Any idea ? for make it better a better magnet effect

The best approach will be adding a special effect script to affected objects instead of manipulating their physics:

public class Magneted:MonoBehaviour{
private float transitionState;
public Transform target;
private float initialD;

void Start(){
initialD = Vector2.Distance(transform.position,target.position);
rigidbody2D.isKinematic=true;
}

void Update(){
transitionState+=Time.deltaTime;
if(transitionState>1F){
//Being added to inventory code
return;
}
float tdiff = initialD*transitionState;
float ad = Vector2.Distance(transform.position,target.position);
if(ad>tdiff){
Vector2 npos = Vector2.MoveTowards(transform.position, target.position, ad-tdiff); 
transform.position=npos;
}

}}

It might not even compile but this will give you general idea :slight_smile: