AS3 - Changing depth of MC in relation to another

2019-09-06 18:31发布

问题:

I am trying to make this top-down game that uses slightly 3D sprites. I want to be able to make the player walk in front of, as well as behind, any object he comes to.

Like, if he's a certain distance behind another object, he'll move behind it and if he's closer to the front of the other object, he'll move in front of it.

Kind of like those old arcade games like streets of rage.

Any ideas?

回答1:

everytime the player moves, you need to evaluate the y position of each applicable item and sort the z-order/childIndex based off that.

so if all your 'objects' to walk behind/infront of and your character were in a parent sprite called foreground:

function sortZ(){
    var arrayOfStuff:Vector<DisplayObject> = new Vector<DisplayObject>();

    var i:int;
    for(i=0;i<foreground.numChildren;i++){
        arrayOfStuff.push(foreground.getChildAt(i));
    }

    arrayOfStuff.sort(sortArrayByY);

    for(i=0;i<arrayOfStuff.length;i++){
        foreground.setChildIndex(arrayOfStuff[i],i);
    }
}

function sortArrayByY(valA:DisplayObject, valB:DisplayObject):int {
    if(valA.y == valB.y) return 0;
    if(valA.y > valB.y) return 1;
    return -1;
}