Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Help a noob plz! OnTriggerEnter and Vector2 problems

Discussion in '2D' started by Markof, Mar 27, 2015.

  1. Markof

    Markof

    Joined:
    Mar 26, 2015
    Posts:
    5
    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 :/ 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 <GameObject> ();
    }

    // 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);
    }
    }
    }
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    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:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Magnetic : MonoBehaviour
    5. {
    6.     // Negative repel
    7.     private bool negativeDown;
    8.  
    9.     public float magnetForce = 10f;
    10.  
    11.     Vector2 forceDirection;
    12.  
    13.     Rigidbody2D rigidBody2D;
    14.  
    15.     void Awake()
    16.     {
    17.         negativeDown = true;
    18.  
    19.         rigidBody2D = GetComponent<Rigidbody2D>();
    20.     }
    21.  
    22.     void OnTriggerEnter2D(Collider2D other)
    23.     {
    24.         //Magnet Above, negative down
    25.         if (gameObject.transform.position.y > other.transform.position.y && negativeDown == true)
    26.         {
    27.             rigidBody2D.AddForce(new Vector2(0, -magnetForce));
    28.         }
    29.     }
    30. }