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

2D Flying to an object, and then passing it.

Discussion in 'Scripting' started by Punfish, Dec 11, 2014.

  1. Punfish

    Punfish

    Joined:
    Dec 7, 2014
    Posts:
    327
    Regrettably I don't have my code on hand to demonstrate my progress; but, what I'm attempting to do is fly to an object and then keep flying past that object, eventually moving off screen.


    I've been able to move to a specific object without issue but I am having difficulties flying PAST said object.

    Ultimately I just want to send something in a certain direction and keep it moving that way. This is for a 2D game, similar to Asteroids.
     
  2. fox4snce

    fox4snce

    Joined:
    Jan 25, 2014
    Posts:
    74
    You don't need to fly to the object unless the object is moving.

    If the object is not moving, I think you can do something like

    Code (CSharp):
    1.  
    2. Vector2 v; // vector I want to move in
    3. v = target.position - ship.position;
    4.  
    Then you just fly in that direction until you're out of the world. You can then do...

    Code (CSharp):
    1.  
    2. v.Normalize();  // to get a vector with magnitude 1
    3.  
    And multiple each component by the speed you want. Then just do

    Code (CSharp):
    1.  
    2. ship.position = new Vector2(ship.position.x + v.x, ship.position.y + v.y);
    3.  
    If you're using physics, you have to rotate toward the target point, then add a force to fly in that direction. If there's no drag you'll just keep flying.

    It's a whole other issue if the object you're flying to is moving.

    There should be plenty out there. Mostly you can just keep turning toward the object you're flying toward, moving in that way, then when you reach the object, just keep flying in the same direction instead of turning again.

    Hope that helps :)
     
  3. Punfish

    Punfish

    Joined:
    Dec 7, 2014
    Posts:
    327
    I'm sure I can work something out. I found a lot of information but ultimately I had the problem of not being able to fly past the object. There is no drag on the object I'm moving, and it is moving to a stationary target. However, the object does rotate to give the spinning illusion. I'll mock up something when I get a chance and post my findings.
     
  4. Punfish

    Punfish

    Joined:
    Dec 7, 2014
    Posts:
    327
    I'm actually wondering if rotating the item after a push will make it move in a circle. I have a feeling that it may.