How to use a movieclip as a boundary for another dragable object in AS3?

£可爱£侵袭症+ 提交于 2019-12-11 06:37:38

问题


How to use a movieclip as a boundary for another dragable object?

All I know is, we can use a rectangle for boundary in start drag .

dragable_mc.addEventListener(MouseEvent.MOUSE_DOWN, start_drag);
function start_drag(e:MouseEvent)
{
    var rect:Rectangle = new Rectangle(0,0,100,100);
    dragable_mc.startDrag(false, rect);
}

What is the way to drag a movieclip in another movieclip in flash by as3? (like as I shown in pic)


回答1:


If it is a dynamic shape, you'd have to log the x,y coordinates of the drag-able object every frame upon drag. Then do a bitmap-hitpoint test with the boundary to check if the object is out of bounds. If it is outside, return to the last coordinates that isn't out of bound.

edit:

The two variables you need to rename are dragTarget and bound_mc

dragTarget is your dragable_mc

bound_mc is the name of the movieclip of your boundary.

bound_mc need to be in png format, and the out of bounds area MUST be transparent. example:

import flash.geom.Point;
import flash.geom.Rectangle;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.BitmapData;

stop();

var bmd:BitmapData =new BitmapData(600, 400, true, 0x000000);
var rect:Rectangle;
var lastPt:Point = new Point();

function init():void {
    rect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
    setUpBitmap();
}

function setUpBitmap():void {
    bmd.draw(bound_mc);

    dragTarget.addEventListener(MouseEvent.MOUSE_DOWN, start_drag);
}

function start_drag(event:MouseEvent):void {
    dragTarget.removeEventListener(MouseEvent.MOUSE_DOWN, start_drag);
    stage.addEventListener(MouseEvent.MOUSE_UP, stop_drag);

    lastPt.x = dragTarget.x;
    lastPt.y = dragTarget.y;

    dragTarget.startDrag(false, rect);
    this.addEventListener(Event.ENTER_FRAME, logPoint);
}

function stop_drag(event:MouseEvent):void {
    this.removeEventListener(Event.ENTER_FRAME, logPoint);
    stage.removeEventListener(MouseEvent.MOUSE_UP, stop_drag);
    dragTarget.addEventListener(MouseEvent.MOUSE_DOWN, start_drag);

    dragTarget.stopDrag();
}

function logPoint(event:Event):void {
    var curPoint:Point = new Point(stage.mouseX, stage.mouseY);

    if ( bmd.hitTest(new Point( bound_mc.x, bound_mc.y ), 0, curPoint) ) {
        lastPt = curPoint;
    } else {
        dragTarget.x = lastPt.x;
        dragTarget.y = lastPt.y;

        stage.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP));
    }
}

init();


来源:https://stackoverflow.com/questions/55530091/how-to-use-a-movieclip-as-a-boundary-for-another-dragable-object-in-as3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!