Help a noob plz! OnTriggerEnter and Vector2 problems

Hello everyone,

Im new to Unity and Im trying to prototipe a magnet efect. When the magnet comes close to any metal, I want to add some forces to repel or to atrac it to the metal. The game is a 2D platformer.

I have wrote this, but it does nothing :confused: help plz!


using UnityEngine;
using System.Collections;

public class PlayerMagnet : MonoBehaviour {
//negative repel
private bool negativeDown;

public float magnetForce = 10f;

GameObject magnet;
Vector2 forceDirection;

// Use this for initialization
void Awake () {
negativeDown = true;
magnet = GetComponent ();
}

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

}

void OnTriggerEnter (Collider other){
//Magnet Above, negative down
if (magnet.transform.position.y > other.transform.position.y && negativeDown == true) {
forceDirection.Set (0f, magnetForce);
}
}
}

Since youโ€™re posting in the 2D forum, I assume you use the 2D physics, however your code uses 3D physics. Try something like this instead:

using UnityEngine;
using System.Collections;

public class Magnetic : MonoBehaviour
{
    // Negative repel
    private bool negativeDown;

    public float magnetForce = 10f;

    Vector2 forceDirection;

    Rigidbody2D rigidBody2D;

    void Awake()
    {
        negativeDown = true;

        rigidBody2D = GetComponent<Rigidbody2D>();
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        //Magnet Above, negative down
        if (gameObject.transform.position.y > other.transform.position.y && negativeDown == true)
        {
            rigidBody2D.AddForce(new Vector2(0, -magnetForce));
        }
    }
}