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

Sling mechanic AddForce direction

Discussion in 'Scripting' started by echoic, Jun 26, 2015.

  1. echoic

    echoic

    Joined:
    Apr 29, 2011
    Posts:
    89
    Hi coders,

    I have a character (yellow in the picture) who orbits a tiny sphere (blue) while holding the space bar. I'm trying to make him fly off in the appropriate direction when releasing the space bar. lastTarget.transform.position - transform.position works okay, but it doesn't really feel natural, given the characters direction of orbit.

    On the screen shot, I've marked the direction the character will fly if the space bar were to be released at that given phase of the orbit. I've also marked the direction I would prefer the character to fly.

    Here's the code I'm using to add force. Any ideas would be much appreciated. Thanks!

    if (Input.GetKeyUp("space")) {

    meter.localScale.x = 0;

    if (currentPlanet != null) {

    orbitPhase = 0;
    lastTarget = currentPlanet;
    currentPlanet = null;
    var dir = lastTarget.transform.position - transform.position;
    //Debug.Log(dir);
    dir = dir.normalized;
    rigidbody2D.AddForce(-dir * Mathf.Clamp(slingForce,-2500,2500));
    slingForce = startSlingForce;

    }


    }
     

    Attached Files:

  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Do they rotate as they orbit? If so, you could use transform.forward as the direction of choice.
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    You want a direction perpendicular to dir.

    From memory something like this. (you'll want to deal with the special case where dir.z == 0).

    Code (csharp):
    1. new Vector3 (1,0,-dir.x/dir.z).normalised
     
  4. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    974
    I think we'll need to see the rest of the code.. There's not enough info here for me to hazard a guess.
    When you post, please use Code Tags.

    One option would be to track the movement of the yellow sphere between last frame and current frame - the difference would give you a vector with approximately the correct direction.
     
  5. echoic

    echoic

    Joined:
    Apr 29, 2011
    Posts:
    89
    Great replies. It's working how I want now. Thanks all!