Search code examples
actionscript-3stage

How to make a MovieClip stick to the Flash player edge?


I have been starting to code in ActionScript, and tried to do this program. It draws a shape into the stage, and you can move it using the arrow keys. I added a "edge sticking" feature that sticks half of the shape to the edge. here's my code:

function freemove(event:KeyboardEvent):void
{
    switch (event.keyCode)
    {
        case Keyboard.UP:
        {
            testing.y -= 5;
            if(testing.y < stage.width)
            {
                testing.y = 0;
                }
            break;
        }
        case Keyboard.DOWN:
        {
            testing.y += 5;
            // FOR BOTTOM EDGE.
            break;
        }
        case Keyboard.LEFT:
        {
            testing.x -= 5;
            if(testing.x < stage.height)
            {
                testing.x = 0;
                }
            break;
        }
        case Keyboard.RIGHT:
        {
            testing.x += 5;
            // FOR RIGHT EDGE.
            break;
        }
        }

    }

The problem is: It only works for the left and top edge. How can I make it work for the bottom and right edge? Thanks! =)


Solution

  • // FOR BOTTOM EDGE.
    if (shape.y + shape.height > stage.stageHeight)
    
    // FOR RIGHT EDGE.
    if (shape.x + shape.width > stage.stageWidth)
    

    Also, you might confuse width and height in your LEFT and RIGHT handlers (why y is compared with width and x with height?)