Search code examples
actionscript-3flashactionscriptflash-cs5flash-cs4

make a movie clip come back up after going down to a certain depth automatically


hi please have a look at the code. When I press keyboard the object goes down however what I want is that when it reached a certain depth it should come back..any help would be appreciated , thank you

//rope coding
var rope = MovieClip(this.root).boat_mc.rope_mc;
var ropeMove:Boolean = false;

    stage.addEventListener(Event.ENTER_FRAME, ropeCode);
    stage.addEventListener(KeyboardEvent.KEY_UP, onSpacebarUp);

    function onSpacebarUp(e:KeyboardEvent):void
    {
        if (e.keyCode == Keyboard.SPACE)
            ropeMove = !ropeMove; // toggles ropeMove (i.e. if it's true, sets it to false, and vice versa)
    }

    function ropeCode(e:Event):void
    {
        //check direction of rope
        if(yDirection) 
        {
          rope.y += ropeSpeed;
        }
        else
        {
          rope.y -= ropeSpeed;
        }


        // move the rope
        if( ropeMove )
        {
            if( rope.y < 230) 
            {
                yDirection = true;
                trace(rope.y);
            }
            // stop moving if we've gone too far
            else if (rope.y > 230) 
            {
                yDirection = false;
            }
        }



    }

Solution

  • You have 2 checks like

    if( rope.y < 230)
    

    and

    if( rope.y > 230)
    

    I think your animation could get stuck when y is 230 so make one of those to test for equality like

    if( rope.y < =230)
    

    or add a third case

    else if(y==230)
    

    Edit: add a new variable/field named yDirection

    var yDirection:Boolean=true;
    

    when you want to change the direction flip this flag

    if( rope.y <=0)
      yDirection=true;
    else 
      yDirection=false;
    
    if(yDirection)
      rope.y=+=speed;
    else
      rope.y-=speed;
    

    EDIT2 Hi had a bug in previous edit, replace the rope.y <=0 with the value you need (minY value)

    EDIT3 The solutions is easy, you must check the ropeMove value,

    if(ropeMove){
    
        if( rope.y <=0)
          yDirection=true;
        else 
          yDirection=false;
    
        if(yDirection)
          rope.y=+=speed;
        else
          rope.y-=speed;
    } 
    

    Your questions are very basic so you should learn the basics of algorithms,