Adobe Edge Animate : How to get Symbol's current time? - adobe-edge

In Adobe Edge Animate, how to get Symbol's current time ?
I use a mix of jQuery & Adobe Edge codes to program my page. I want to check if a symbol's time stays at first frame (if in Flash's concept).
$(window).scroll(function(e)
{
var the_stage = $.Edge.getComposition("EDGE-123456").getStage();
var sym = the_stage.getSymbol(id);
// how to get current time ?
});

Finally found a solution. To get the current time, use:
var pos = sym.getPosition()
pos is an integer . If the symbol hasn't played before, its value is -1, else it is the position in milliseconds.

Your solution is ok, but need clarification.
If your animation is "inside" the div:
<div id="stage_animation_0" class="animation_0"></div>
I suggest to name class attribute with "animation_" + animation number and id attribute with "stage_" + class name.
GET
You can obtain actual timeline position in this way:
var getAnimationPos = function(animation) {
var stage = $.Edge.getComposition(animation).getStage();
var sym = stage.getSymbol("stage_" + animation);
return sym.getPosition();
}
In this way you can obtain your timeline position with:
var position = getAnimationPos("animation_0");
SET
Setting the actual timeline position is more "complicated".
If your animation is playing and you want to jump to a specific position:
var jumpPosition = 300; /* expressed in milliseconds */
$.Edge.getComposition(animation).getStage().play(jumpPosition);
If your animation is paused and you want to set position without play, you have to:
var jumpPosition = 300; /* expressed in milliseconds */
$.Edge.getComposition(animation).getStage().stop(jumpPosition);
In this way, when you'll call play(), animation will start from position 300.

Related

Vertical paper-slider element

I like the Polymer paper elements and I want to use a paper-slider element.
However, i would like it to be vertical. I've tried to apply css to rotate it;
transform: rotate(90deg);
This rotates the slider, but not the "input"; one must still click and drag the mouse horizontally in order to get the "knob" to move up and down.
This is very annoying and any help is rely appreciated!
tk-vslider is a tweaked paper-slider with rotate functionality. Use this instead of paper-slider to solve this issue. Install using bower "tkvslider": "0.5.5"
<tk-vslider rotate="true"></tk-vslider>
Tweaks.
if rotate == true then
div#sliderContainer is css rotated by 90deg
Event on-trackx of the div#sliderKnob is replaced by on-track
In the method tracktake e.dy instead of e.dx.
This might be a pretty hacky way to do it, but we're coming up a year since you requested this as feature and it doesn't look like it's much of a priority yet. I figure this will (for the most part) allow for continued updates of paper-slider from the Polymer team without depending on third parties that might not continue support (from what I can tell, the custom element tk-vslider mentioned here hasn't been updated to support Polymer 1.0).
First, the css. I found that if I rotated 90 degrees, the smaller values were at the top of the slider, which I found to be counter-intuitive. So instead I rotate by -90. Some weird stuff happens with the margins but this is what finally did it for me:
paper-slider {
width: 20vh;
margin: 10vh -10vh;
--webkit-transform: rotate(-90deg);
transform: rotate(-90deg);
}
I had my paper-slider inside my own custom element, so I put the following code in the ready callback, but I imagine you could put it anywhere you needed, as long as you can select the slider element. We're basically just going to override the method that paper-slider uses to respond to drag events. Here's how:
var slider = this.$.slider;
slider._trackX = function(e) {
if (!slider.dragging) {
slider._trackStart(e);
}
var dx = Math.min(slider._maxx, Math.max(slider._minx, (-1 * e.detail.dy)));
slider._x = slider._startx + dx;
var immediateValue = slider._calcStep(slider._calcKnobPosition(slider._x / slider._w));
slider._setImmediateValue(immediateValue);
// update knob's position
var translateY = ((slider._calcRatio(immediateValue) * slider._w) - slider._startx);
slider.translate3d(translateY + 'px', 0, 0, slider.$.sliderKnob);
};
Almost the entirety of this method is copied over from paper-slider source code, the only real change is that instead of grabbing the x coordinate in e.detail.dx we grab the y in e.detail.dy. The negative multiplier is only necessary if you want smaller values at the bottom of your slider, and you rotated your paper-slider by -90 degrees. Note that if the Polymer team ever changes the name of the method _trackX, it'll break this solution. I know this is a bit late but hopefully it'll help anyone else finding themselves in a similar situation (as I did).
UPDATE: Probably should have tested this solution a bit more, turns out there's another function that needs to be overwritten to handle click events (the other one only handles drag). I got it to work by adding this below my other method:
slider._bardown = function(event) {
slider._w = slider.$.sliderBar.offsetWidth;
var rect = slider.$.sliderBar.getBoundingClientRect();
var ratio = ((rect.bottom - event.detail.y) / slider._w);
var prevRatio = slider.ratio;
slider._setTransiting(true);
slider._positionKnob(ratio);
slider.debounce('expandKnob', slider._expandKnob, 60);
// if the ratio doesn't change, sliderKnob's animation won't start
// and `_knobTransitionEnd` won't be called
// Therefore, we need to manually update the `transiting` state
if (prevRatio === slider.ratio) {
slider._setTransiting(false);
}
slider.async(function() {
slider.fire('change');
});
// cancel selection
event.preventDefault();
}
The main change to this method is the line that calculates the ratio. Before it was var ratio = (event.detail.x - rect.left) / this._w;
<s-slider> has vertical property for vertical orientation https://github.com/StartPolymer/s-slider
zberry's answer didnt work for me anymore. However, I took his answer and updated it. The Polymer3 solution to make the paper-slider vertically responsive would look like this (given the same CSS zberry used):
let slider = this.shadowRoot.querySelector('paper-slider');
slider._trackX = function(event) {
if (!slider.dragging) {
slider._trackStart(event);
}
var dx =
Math.min(slider._maxx, Math.max(slider._minx, -1 * event.detail.dy));
slider._x = slider._startx + dx;
var immediateValue =
slider._calcStep(slider._calcKnobPosition(slider._x / slider._w * 100));
slider._setImmediateValue(immediateValue);
// update knob's position
var translateX =
((slider._calcRatio(slider.immediateValue) * slider._w) -
slider._knobstartx);
slider.translate3d(translateX + 'px', 0, 0, slider.$.sliderKnob);
};
slider._barclick = function(event) {
slider._w = slider.$.sliderBar.offsetWidth;
var rect = slider.$.sliderBar.getBoundingClientRect();
var ratio = (rect.bottom - event.detail.y) / slider._w * 100;
if (slider._isRTL) {
ratio = 100 - ratio;
}
var prevRatio = slider.ratio;
slider._setTransiting(true);
slider._positionKnob(ratio);
// if the ratio doesn't change, sliderKnob's animation won't start
// and `_knobTransitionEnd` won't be called
// Therefore, we need to manually update the `transiting` state
if (prevRatio === slider.ratio) {
slider._setTransiting(false);
}
slider.async(function() {
slider.fire('change', {composed: true});
});
// cancel selection
event.preventDefault();
// set the focus manually because we will called prevent default
slider.focus();
};
If you want to slide from top to down you have to fiddle with the directions

AS3 Psuedo 3D Z-Indexing

I am attempting to make a really basic Pseudo 3D game in AS3. When I press certain keys my character moves up and down but what I want to happen is when the characters y position is above an objects y position then the character should appear behind the object.
Here is my code for an objects class at the moment:
package {
import flash.display.MovieClip;
import flash.utils.getTimer
import flash.events.Event;
public class bushMC extends MovieClip {
private var lastFrame:int = new int(0);
private var dt:Number = new Number();
private var main:Main;
public function bushMC(){
main = this.parent as Main;
stage.addEventListener(Event.ENTER_FRAME, update);
trace(main.getChildIndex(this));
}
private function update(e:Event):void{
dt = (getTimer() - lastFrame)/30;
lastFrame = getTimer();
if(main.char.y + 200 < this.y + 55 && main.getChildIndex(main.char) > main.getChildIndex(this)){
main.setChildIndex(this, main.getChildIndex(main.char)+1);
}
else if(main.getChildIndex(main.char) < main.getChildIndex(this)){
main.setChildIndex(this, main.getChildIndex(main.char));
}
}
}
}
I have tried editing loads of the values(+1, -1, equal to) for each calculation but I can't seem to find the right ones. One I tried almost works but instead when the char is supposed to be behind the object it simply flickers in-front and then behind continuously.
Thanks in advance, Kyle.
I just tried a little quick mock script based off your code. I got it working how I assume you are attempting to get it to work:
import flash.events.Event;
import flash.display.MovieClip;
var char:MovieClip = new MovieClip();
var bush:MovieClip = new MovieClip();
char.graphics.beginFill(0xFF0000);
char.graphics.drawCircle(0, 0, 30);
bush.graphics.beginFill(0x00FF00);
bush.graphics.drawEllipse(0, 0, 40, 80);
this.addChild(char);
this.addChild(bush);
bush.x = 100+(Math.random()*350);
bush.y = 100+(Math.random()*200);
this.addEventListener(Event.ENTER_FRAME, updateYPos);
function updateYPos(e:Event):void {
char.x = mouseX;
char.y = mouseY;
if(char.y < bush.y + 30 && this.getChildIndex(char) >= this.getChildIndex(bush)){
this.setChildIndex(bush, this.getChildIndex(char));
}
else if(char.y > bush.y + 30 && this.getChildIndex(char) < this.getChildIndex(bush)){
this.setChildIndex(bush, this.getChildIndex(char));
}
}
I hope this sample is enough to help you. All it needed was an extra condition on the else if and it works. :)
You should have a sorted list of bushes somewhere, which is then added via addChild() in the right order - uppermost bush has lowermost Z-position (child index 0 or the least of bushes, there could be other objects). Then, as your player moves, you track its position relative to list of bushes, so you don't run the full list check for z-ordering of player, but only check "nearest" bushes for possible change, then you set child index of player to found value. Note that if you're setting child index of player to bush's index, if you are moving player forwards (greater indexes), set to -1, as the bush will actually be one position lower because of player occupying a position in the display list, and if you are setting child index to lower values, set to equal. There is a more elegant version of this, using the fact that your bushes are continuous within display list, with only interruption being player, although it will run out of steam once more moving objects will appear.
And yes, you run update on the player or any other moving objects, not on the bush.
function updateZPos(e:Event):void {
// process coordinates change
var p:DisplayObjectContainer=this.parent;
// a bit faster to use function local var to get parent
var ci:int=p.getChildIndex(this); // changeable, get current index
var prev:DisplayObject=null;
if(ci>0) prev=p.getChildAt(ci-1);
var next:DisplayObject=null;
if(ci<p.numChildren-1) next=p.getChildAt(ci+1);
while(prev) {
if (this.y<prev.y) {
ci--;
p.setChildIndex(this,ci);
if (ci>0) prev=p.getChildAt(ci-1); else prev=null;
} else break;
while(next) {
if (this.y>next.y) {
ci++;
p.setChildIndex(this,ci);
if(ci<p.numChildren-1) next=p.getChildAt(ci+1); else next=null;
} else break;
}
}
This function was written with implication of display list of p being pre-sorted, and will maintain sorted state of it after moving of this, and is suitable for any moving object, not just the player. For this to work without messing up your other objects, separate everything moving into one container which will then get referenced as base for sorting display list. Otherwise your player might eventually get above all as the last element to check will be say score textfield with Y of 0. Also you will need to maintain coherent position of register point all over your set of moving objects' classes, so that say the base of a bush will be at Y=0 instead of being at Y=30, as implied in your code. The legs of a player should then also be at Y=0.

AS3 Clicking in "zones" of a picture

I have searched and simply cannot find what I need (if it exists).
A window will have a large picture.
The picture will be divided into zones (such as border lines that separate states on a map).
When a person clicks within a zone, then I will raise the appropriate event.
I've used AS3 with MXML to create a database program. All is working great except for this last step. I cannot figure out how the user is within a particular area of the picture when he clicks or when he touches.
I've read and tried to come up with an approach, and there must be (hopefully so) an easier way than the muddled nonsense I'm coming up with.
Thanks
VL
Are you drawing it in flash professional CS6? If so then why can't you just have the picture as a symbol and then just self divide the lines and make those divided areas into symbols that are children of the picture symbol. You could keep the individual state symbols right where they so that they stay true to the overall picture.
A first thought would be to make an instance of this picture symbol through the code, and then loop though all the children of that picture and add a click event to each one.
var picture:Picture=new Picture();
for(var i:int=0; i<picture.numChildren-1; i++){
picture.getChildAt(i).addEventListener(MouseEvent.CLICK, mouseEventHandler);
}
Please comment if I am missing something, or this does not work.
EDIT
Well, if you know the dimensions of the image, you could divide its width and height by 3(your number of rows and columns) and this is your zone dimensions. You then could take the mouse's click point relative to the top left of your picture and then divide its width by the zone with, and its height by the zone height, and then get its integer floor value, you could get which region it is. Code it below:
//This is all for a constat region list (like a window, or floor tiles, not things irregular)
import flash.display.Sprite;
var regionsX:int = 3; //Your number of windows across the row
var regionsY:int = 3; // across the column
var regions:Array = new Array(); // an array to hold the values that you will get from where the user clicks
// All of this used a 2D array method
for(var x:int = 0; x < regionX; x++) {
regions[regionsX] = new Array();
for(var y:int = 0; y < regionY; y++) {
regions[regionsX][regionsY] = "region(".concat(x).concat(",").concat(y);
// Here you make this equal to anything you want to get a value of,
//once the correct region is found (I just have a string version here for an example)
}
}
... // other stuff..
var picture:Picture = new Picture(); // your window picture
var regionWidth:Number = picture.width / regionsX; // Gets each region's width
var regionHeight:Number = picture.height / regionsY; // Get each regoin's height
...
picture.addEventListener(MouseEvent.CLICK, mouseEventListener); // add a click listener to the picture
function mouseEventListener(event:MouseEvent):void{
var mouseX:Number = picture.globalToLocal(event.stageX); // gets where the user clicked, and then converts it
//to the picture's cordinate space. ( 50,100 acording to the stage, could be (25,200) to the picture)
var mouseY:Number = picture.globalToLocal(event.stageY); // same for the Y
var regionIntX:Number = Math.floor(mouseX / regionWidth); // Dives the point by each region's width, and then
// converts it to a while integer. (For instance, if a region's width is 100 and you click at 288, then if you do the
// math, you clicked in the 3rd region, but it returns 2... why? (becaue the array counter starts at 0, so 0 is the 1st
// region, 1 is the second and so on...
var regionIntY:Number = Math.floor(mouseY / regionHeight); // Same for Y
var yourValue:String = regions[regionIntX][regionIntY]; // This returns that you initialy put into your 2d array
// by using the regionIntX and regionIntY for the array values. You have to decide what is stored in this array...
}
The simplest solution would be to add an event listener for MouseEvent.CLICK to the picture and in the handler check properties mouseX and mouseY of the picture. Define the bounds of each area in an XML or similar and check against current mouseX/Y to see which area has been clicked.

Loop an image in Flash

I want to have a scene where an image which is 5000 pixels high is moving up 5 pixels each frame-refresh. When the image is all up, I'd like to see the top of the image connected to the bottom of the image. This should be done untill the level is 'done'. How can I 'loop' such an Image?
You can create a copy of that image which you keep hidden/above and the trick is to update the position and loop accordingly so when one image goes bellow the screen it goes back on top and repeats.
Here's a basic snippet to illustrate the idea using the DisplayObject class and the scrollRect property:
//ignore this, you have your content already
var dummyContent:BitmapData = new BitmapData(100,100,false);
dummyContent.perlinNoise(10,10,8,12,true,true);
//important stuff starts here
var container:Sprite = addChild(new Sprite()) as Sprite;//make a container
container.scrollRect = new Rectangle(0,0,dummyContent.width,dummyContent.height);//set a scrollRect/'mask'
var part1:DisplayObject = container.addChild(new Bitmap(dummyContent));//add two copies
var part2:DisplayObject = container.addChild(new Bitmap(dummyContent));//of the same content
part2.y -= part2.height;//set the 2nd at the top of the 1st
addEventListener(Event.ENTER_FRAME,update);
function update(e:Event):void{
//move both
part1.y += 5;
part2.y += 5;
//check if any reach the bottom so they can be moved back up
if(part1.y >= part1.height) part1.y = -part1.height;
if(part2.y >= part2.height) part2.y = -part2.height;
//the above can also be nicely placed in a loop if you plan on using more seamless looping clips/images
}
Obviously you will have different content, but the principle is the same.
If you're working with images, you can simply use BitmapData's copyPixels method:
var s:int = 5;//scroll speed
//make some content
var w:int = 100;
var h:int = 100;
var dummyContent:BitmapData = new BitmapData(w,h,false);
dummyContent.perlinNoise(10,10,8,12,true,true);
//prepare for stiching
var renderPos:Point = new Point();//position to render the current image to
var prenderPos:Point = new Point();//position to render the previous image (the 'hidden' copy above)
var render:BitmapData = new BitmapData(w,h,false);//create a bitmap data instance to render updated pixels int
addChild(new Bitmap(render));//and add it to the stage
addEventListener(Event.ENTER_FRAME,update);
function update(e:Event):void{
renderPos.y = (renderPos.y+s)%h;//update the scroll position for the 1st part, % is used to loop back to 0 when the position gets to the content height
prenderPos.y = renderPos.y - h;//update the scroll position for the 2nd part (above)
render.lock();//freeze pixel updates
render.copyPixels(dummyContent,dummyContent.rect,renderPos);//copy pixels from the scroll position to the bottom
render.copyPixels(dummyContent,dummyContent.rect,prenderPos);//copy pixels from the top to the scroll position
render.unlock();//unfreeze/update ALL THE PIXELS
}
You can try to use a Rectangle object which changes height (height-scrollPosition) so you potentially access less pixels each time or you can manually work out single for loops using BitmapData's getVector method, but that's something to look into if performance is actually an issue for such a simple task and it's worth checking what's faster ( copy full bitmap rect vs copy partial bitmap rect vs manually copy values using vector )
Be warned, Flash cannot load an image greater than 16,769,025 pixels (or 4095x4095). The height of 5000 pixels will work as long as the width is not greater than 3353.
That said, I'd loop the image by keeping two copies of the image onstage, move both at the same time with a parent object, and reset to origin once your loop point is met.
Consider the following stage setup:
Stage ¬
0: MainTimeline:MovieClip ¬
0: Container:MovieClip ¬
0: img1:Bitmap
1: img2:Bitmap
Now moving container up, you'd just need to check that the looping second image reaches the origin point of the first image.
function onEnterFrame(e:Event):void {
Container.y = Container.y - 5;
if (Container.y < -5000) {
Container.y = -5;
}
}

AS 3 simple ease

How can I move an object and be able to physically see it when it is moving? Not just disappear and appear on a different location like it would be using the following code.
buttonL2_btn.addEventListener(MouseEvent.CLICK, left);
function left(event:Event):void{
box_mc.x =241.5;
}
This is going to move myObject to any location specified, but again I want to be able to see it when moving.
In your example you are just setting it's X position when some button is pressed, when you need to change X into an EnterFrame event, like this:
this.addEventListener(Event.ENTER_FRAME, move);
function move(event:Event):void{
box_mc.x -= 5
}
Your box_mc should move left 5 pixels accordingly with your framerate.
You can use a easing library to that easily. I strongly recommend TweenMax.
Okay I am getting a bit sick of people constantly suggesting some tweening engine. Sure they rock, but it won't help the OP to understand what he is doing.
Kircho to move an object with a really easy tween I suggest the following code in an onEnterFrame event for your object to move:
addEventListener(Event.ENTER_FRAME, onEnterFrame);
var xGoal:Number = 100; //:: The target X destination for your object
var yGoal:Number = 100; //:: The target Y destination for your object
var smothness:Number = 10; //:: Smoothness factor for movement. The lower the value the faster the movement.
function onEnterFrame(e:Event):void
{
box_mc.x += (xGoal - box_mc.x) / smothness;
box_mc.y += (yGoal - box_mc.y) / smothness;
}
Will move/ease your box object to the desired location with a set smoothness.
You can install any of the 437 available tweening engines
or you can add a few lines of code
set up a variable that holds the destination value
var dest:Number = 241.5; // this is what gets updated on mouse click
on enterframe event for box:
function onBoxEnterFrame(e:MouseEvent):void{
if (dest != box_mc.x){
var easeNum:Number = 0.4 // between 0 and 1, the higher the number, the slower the transition
box_mc.x = box_mc.x * easeNum + dest * (1-easeNum);
}
}
you can add a few more lines to snap the position when it is close (less than 0.1 difference) or use a more linear change where you adjust incrementally like box_mc.x += 5; until it matches the dest number