Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question OnTriggerStay2D and Vector2 question

Discussion in '2D' started by sormin, May 4, 2021.

  1. sormin

    sormin

    Joined:
    Apr 25, 2021
    Posts:
    2
    I'm simply trying to get the direction of the collision object in an OnTriggerStay2D so I can addforce to the object with the trigger collider in the same direction. I don't want the velocity, just the direction. The closest I've come to getting it to work is collision.transform.right, but that only sends it right (obviously), and collision.transform.position seems to want to give me the magnitude and all. New at this, any help is appreciated. Thanks!
     
  2. G8S

    G8S

    Joined:
    Feb 7, 2017
    Posts:
    18
    You need to compare the last position to the current position and that will give you the direction. Then when you do OnTriggerEnter2D you can use the direction that you know the object is moving in.

    Something like this on the moving object:

    Code (CSharp):
    1. Vector2 lastPosition;
    2. public Vector2 MovementDirection;
    3.  
    4. void Update()
    5. {
    6.     var currentPosition = new Vector2(transform.position.x, transform.position.y);
    7.     // don't calculate direction when we are standing still
    8.     if(currentPosition != lastPosition)
    9.         MovementDirection = (currentPosition - lastPosition).normalized;
    10.     lastPosition = currentPosition;
    11. }
    Then you can reference it when you want to add force in the direction you are moving

    Code (CSharp):
    1. void OnTriggerEnter2D(Collider2D other)
    2. {
    3.     MovingObject.MovementDirection .....
    4. }
     
  3. sormin

    sormin

    Joined:
    Apr 25, 2021
    Posts:
    2
    Awesome, I'll give it a shot, thanks!