Animate XML data in Flash with Actionscript 3 - javascript

I have a question about getting a specific animation added to some xml data I'm pulling. I need some advice on how to make the data move from left to right or vise versa.Just for example I downloaded a rss feed from BBC world news, so it's just an xml file. Both the flash and xml are saved in the same folder and I can get in flash and display the data. Here's are the code so far:
import flash.text.TextField;
import flash.sampler.StackFrame;
import flash.display.MovieClip;
var yPlacement:int = 20;
var xPlacement:int = 30;
var distance:int = 60;
var loader:URLLoader = new URLLoader();
loader.load(new URLRequest("bbc-worldnews-rss.xml"));
loader.addEventListener(Event.COMPLETE, handleComplete);
function handleComplete(event:Event):void
{
var rawXML:XML = new XML(loader.data);
rawXML.ignoreWhite = true;
//trace(rawXML.channel.image.url);
var items:XMLList = rawXML.channel.item;
//trace("Total new items", items.length());
for each (var item:XML in items)
{
//trace(item.title);
var feedTitle:String = item.title.toString();
var myText:TextField = new TextField();
myText.text = feedTitle;
myText.autoSize = TextFieldAutoSize.LEFT;
myText.x = 2;
myText.y = 2;
var clip_mc = new MovieClip();
clip_mc.addChild(myText);
addChild(clip_mc);
clip_mc.y = yPlacement;
clip_mc.x = xPlacement;
yPlacement = yPlacement + distance;
}
//trace("First item title:", item[0].title);
}
I also know the code that makes text move side to side but I don't know how to incorporate it my codes above:
onClipEvent ( load ) {
startPoint = 1280; //this is where the clip will start
endPoint = -1080; //this is where the clip will end, and restart to the startPoint.
speed = 5; //this is how many pixels the text will move each frame.
}
onClipEvent ( enterFrame ) {
this._x -= speed; //you are telling the MC to move to the left 5 pixels each frame.
if (this._x <= endPoint ) { //if your clip goes beyond the end point.
this._x = startPoint; //go back to the starting point.
}
}
I hope I'm not confusing anyone, I just need to get the data I get from xml file to move side to side... I may be complete off course but I would GREATLY appreciate anyone's help!
Thank you,

For starters, the second snippet of code you posted is actually ActionScript 2, not 3.
You'd need to update that snippet to AS3 in order for this to work. Try something like this:
var startPoint:int = 1280;
var endPoint:int = -1080;
var speed:int = 5;
function moveMC(mc:MovieClip):void {
mc.addEventListener(Event.ENTER_FRAME, tick);
}
function tick(e:Event):void {
e.currentTarget.x -= speed;
if (e.currentTarget.x <= endPoint) {
e.currentTarget.x = startPoint;
}
}
You could then call moveMC() after you've added your newly created MovieClip to the stage.
Edit: You can use that snippet right in your for each loop like this:
for each (var item:XML in items)
{
//trace(item.title);
var feedTitle:String = item.title.toString();
var myText:TextField = new TextField();
myText.text = feedTitle;
myText.autoSize = TextFieldAutoSize.LEFT;
myText.x = 2;
myText.y = 2;
var clip_mc = new MovieClip();
clip_mc.addChild(myText);
addChild(clip_mc);
clip_mc.y = yPlacement;
clip_mc.x = xPlacement;
yPlacement = yPlacement + distance;
//takes in reference to MovieClip, start point, end point and speed
moveMC(clip_mc, 1280, -1080, 5);
}
function moveMC(mc:MovieClip, startPoint:int, endPoint:int, speed:int):void {
mc.startPoint = startPoint;
mc.endPoint = endPoint;
mc.speed = speed;
mc.addEventListener(Event.ENTER_FRAME, tick);
}
function tick(e:Event):void {
var mc:MovieClip = e.currentTarget as MovieClip;
mc.x -= mc.speed;
if (mc.x <= mc.endPoint) {
mc.x = mc.startPoint;
}
}

Related

[indesign][js] dialog or palette - not show up

have problem with script.
need open a window with some information, which will automatically disappear after 3 seconds.
my code:
#targetengine "session"
var windowX = new Window("dialog"); // v2 palette
windowX.orientation = "row";
windowX.preferredSize.width = 200;
windowX.preferredSize.height = 200;
windowX.alignChildren = ["center","center"];
windowX.spacing = 15;
windowX.margins = 16;
var image1_imgString = "%C2%89PNG%0D%0A%1A..."
var image1 = windowX.add("image", undefined, File.decode(image1_imgString), {name: "image1"});
windowX.show();
dialog show, palette not
if I add ...
var timerBreak = new Date().getTime() + 3000;
var now = new Date().getTime();
while(now<timerBreak){
now = new Date().getTime()
}
windowX.close();
nothing happend (happend: first: loop, next: window show and close at the same time) - why?
if i add ...
windowX.addEventListener('show',function(){
...
}
same ...
but if i add alert("dhgkjsd") ... for check ... dialog (or palette) show and wait for click on messagaebox
how to make a timer that will close the displayed window 3 seconds after opening?
Unfortunately, I do not have a copy of InDesign to test this, but the code below works in AfterEffects.
#targetengine "session"
// To be called later
function closeMe() {
windowX.close();
}
// Timer as a variable
var delay = 3000;
// a pallette, and not a modal, like in your
// original code, because the modal is UI blocking
var windowX = new Window("palette");
windowX.orientation = "row";
windowX.preferredSize.width = 200;
windowX.preferredSize.height = 200;
windowX.alignChildren = ["center","center"];
windowX.spacing = 15;
windowX.margins = 16;
windowX.show();
// This is the key part
app.setTimeout(closeMe,delay);
app.setTimeout() has been suggested as a way of delaying code execution, which is what you need in this case (delaying of windowX.close()). Please note the author's comments (check the link) - app.setTimeout() has been made available from AE version CC 2015.
It can be done this way:
var windowX = new Window("palette");
windowX.orientation = "row";
windowX.preferredSize.width = 200;
windowX.preferredSize.height = 200;
windowX.alignChildren = ["center","center"];
windowX.spacing = 15;
windowX.margins = 16;
// var image1_imgString = "%C2%89PNG%0D%0A%1A..."
// var image1 = windowX.add("image", undefined, File.decode(image1_imgString), {name: "image1"});
windowX.show();
// here is the magic
windowX.update();
$.sleep(3000); // 3 seconds
windowX.hide();
windowX = null;
Based on the example from here: https://community.adobe.com/t5/illustrator-discussions/auto-close-alert-message/td-p/9398258
#Yuri ... windowX don't show before $.sleep (use instead var timerBreak...) - but only my Mac. Another Mac - your code works.
I write something like this:
//create windowX
var oneIdleTask = app.idleTasks.add({
name: "one_idle_task",
sleep: 1
}); // sleep not working here - write 3000 and nothing change
var onIdleEventListener = oneIdleTask.addEventListener(IdleEvent.ON_IDLE,
function() {
var oneIdleTaskName = "one_idle_task";
var oneIdleTask = app.idleTasks.itemByName(oneIdleTaskName);
if (oneIdleTask != null) {
oneIdleTask.remove();
$.sleep(3000) //<- write sleep here ... but deley is ok (for me) without this
windowX.hide();
}
}
);
windowX.show();

Convert a sync js function with blocking for loop for websocket updates to html table to async - JS/JQuery

I have a sync function which is blocking the DOM causing updates to slow down in javascript. Is it possible to convert it to an async function?
function setBids(gapPrice)
{
var startBuyPrice = this.bid
gapPrice=parseFloat(gapPrice)
var showMaximum = 15
var startBuyViewPrice = Math.floor(startBuyPrice/gapPrice)*gapPrice
var tmpOrder = {price:null,size:null,total: null}
var currentBuyViewPrice = startBuyViewPrice
var totalBuy=0;
var buys="";
var cntShow = 0
for(var price = startBuyPrice;cntShow<showMaximum;price -= 0.5)
{
if(this.orderBook[price]==undefined)
continue
var tmpSize = this.orderBook[price].size;
if(currentBuyViewPrice>price)
{
currentBuyViewPrice -= gapPrice
tmpOrder['size'] = new Intl.NumberFormat('en-US').format(tmpOrder['size'])
tmpOrder['total'] = new Intl.NumberFormat('en-US').format(totalBuy)
tmpOrder['price'] = new Intl.NumberFormat('en-US').format(tmpOrder['price'].toFixed(1))
if(tmpOrder['price'].indexOf('.')==-1)
tmpOrder['price'] += '.0'
buys+='<tr><td style="color:white !important;">'+tmpOrder['total']+'</td><td style="color:white !important;">'+tmpOrder['size']+'</td><td>'+tmpOrder['price']+'</td></tr>'
tmpOrder = {price:null,size:null,total: null}
cntShow += 1
}
totalBuy+=tmpSize;
if(tmpOrder['price']==null)
{
tmpOrder['price'] = currentBuyViewPrice
tmpOrder['size'] = tmpSize
}
else
{
tmpOrder['size'] += tmpSize
}
}
$(".orderbook-table-bids tbody").html(buys)
}
When websockets update come, this function is called frequently, setting showMaximum to 1 does not have an issue because the loop does not block, anything above 1 causes the page to hang.
Thanks in advance.

Js function always return the same values

Js beginner here.
I have a function like this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay,delay);
};
var playAudioOnDelay = function() {
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
};
}
}
What it does is generate data from JSON and display animated elements one by one on delay. Animation part work fine. I can assign required animations and delay to DOM elements and show them in right order.
But what I want to do in the same time is also to play an audio on delay (so I use setTimeout). Everything is almost fine, I play audio in right time (correct delay value) but I always play the same audio (which is last element) because audioPlayer always is the same DOM node.
I think this have something to do with this or I mixed a scope?
Try this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay(audioPlayer),delay);
};
}
function playAudioOnDelay(audioPlayer){
return function(){
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
}
}
}
Essentially, your problem looks like this: http://jsfiddle.net/po0rLnwo/
The solution is : http://jsfiddle.net/gpfuo1s8/
Check the console in your browser.

Javascript error: object is not a function in a video poker script

So I have been writing a script to play a video (or really text-based) poker game as an exercise in learning Javascript. I have everything working to play through an instance of the game once, but on trying to run it a second time, it develops an error: "Uncaught TypeError: object is not a function"
This error comes up when trying to create a new hand.
Here is the relevant code, I left a few functions out that don't seem to be causing any issues:
//object constructor for card
function card(suite, faceValue) {
this.suite = suite,
this.faceValue = faceValue
}
//object constructor for hand
function hand(cards, handName, score, docHandName) {
this.cards = cards,
this.handName = handName,
this.score = score,
this.docHandName = docHandName
}
var deck = new Array;
var buildDeck = function() {
for (var i = 0; i <= 52; i++) {
if (i < 13) {
deck[i] = new card("Spades", i + 2);
}
else if (i < 26) {
deck[i] = new card("Clubs", i - 11);
}
else if (i < 39) {
deck[i] = new card("Hearts", i - 24);
}
else if (i < 52) {
deck[i] = new card("Diamonds", i - 37);
}
}
}
//pulls a card from location in deck specified by randomSpot()
var pullCard = function(spot) {
var newCard = deck[spot];
deck.splice(spot, 1);
return newCard;
}
//takes away a card each time
//passes into pullCard(spot) as spot
var pullCount = 0;
var randomSpot = function() {
var x = Math.floor(Math.random() * (52 - pullCount));
pullCount++;
return x;
}
var dealFiveCards = function() {
var card1 = pullCard(randomSpot());
var card2 = pullCard(randomSpot());
var card3 = pullCard(randomSpot());
var card4 = pullCard(randomSpot());
var card5 = pullCard(randomSpot());
var fiveCards = [card1, card2, card3, card4, card5];
return fiveCards;
}
function createNewHand() {
newHand = new hand();
newHand.cards = dealFiveCards();
return newHand;
}
var playOneGame = function() {
buildDeck();
hand = createNewHand();
hand.cards.sort(compare);
assignHandScore();
wager = prompt("How much do you bet?");
printHandValue();
dealAgain();
hand.cards.sort(compare);
assignHandScore();
payout = pays(wager);
printHandValue();
printPayout();
}
playAgain = "Y";
while (playAgain === "Y") {
playOneGame();
playAgain = prompt("Would you like to play again? Y/N").toUpperCase();
}
So the error occurs when trying to run the playOneGame() function a second time. The first time runs fine and a hand is created. The second time when it gets to hand = createNewHand(); it gives the object is not a function error.
To be clear, I have the hand created as an object, which contains properties cards, handName, score, docHandName where cards is an array of card objects, themselves containing properties of suite, faceValue.
The error gives the line newHand = new hand(); in function createNewHand() as the reference line.
Help?
The second line of playOneGame is overriding your global hand function with an instance of hand. So when createNewHand runs again hand it is no longer the same thing.
You should probably rename the function hand to Hand.

How many points can a Cesium Map display?

I am trying to put thousands of points on a Cesium map and running into problems with Firefox crashing. I am required to use Firefox. The map seems to be able to display 15,000 points (as images). However, it is also almost unusable. Zooming and panning have huge delays and eventually crash. Does anyone know how many points the limit should be? Also, is there a better way to display these points then the way I am doing it? I really hope it's me and not Cesium. I heard that creating czml and then passing it in is slower so I have the following javascript test:
function test(){
for (var i=0; i<15000; i++){
tempLat +=1;
tempLon +=1;
if(tempLat>90){
tempLat=0;
tempLon=0;
}
addBillboard(scene, ellipsoid, tempLat,tempLon);
}
}
//this is from the sandcastle examples for cesium.
function addBillboard(scene, ellipsoid,tempLat,tempLon) {
var primitives = scene.primitives;
var image = new Image();
image.onload = function() {
var billboards = new Cesium.BillboardCollection();
var textureAtlas = scene.context.createTextureAtlas({image : image});
billboards.textureAtlas = textureAtlas;
billboard = billboards.add({
position : ellipsoid.cartographicToCartesian(Cesium.Cartographic.fromDegrees(tempLat, tempLon)),
imageIndex : 0
});
primitives.add(billboards);
};
image.src = '../images/Cesium_Logo_overlay.png';
}
Your code is creating 15,000 BillboardCollection primitives, each with one Billboard each. You will have much better performance if you create one BillboardCollection and add 15,000 Billboards to that collection.
Here's a working example you can use with the b28 release. Paste this into the b28 Sandcastle: http://cesiumjs.org/releases/b28/Apps/Sandcastle/index.html?src=Billboards.html&label=Showcases
Note that some of these APIs will be changing in the upcoming release. Always check CHANGES.md for a list of breaking changes.
require(['Cesium'], function(Cesium) {
"use strict";
var viewer = new Cesium.Viewer('cesiumContainer');
var scene = viewer.scene;
var primitives = scene.primitives;
var ellipsoid = viewer.scene.globe.ellipsoid;
var billboards = new Cesium.BillboardCollection();
var image = new Image();
image.onload = function() {
var textureAtlas = scene.createTextureAtlas({image : image});
billboards.textureAtlas = textureAtlas;
primitives.add(billboards);
};
image.src = '../images/Cesium_Logo_overlay.png';
function addBillboard(tempLat, tempLon) {
billboards.add({
position : ellipsoid.cartographicToCartesian(Cesium.Cartographic.fromDegrees(tempLat, tempLon)),
imageIndex : 0
});
}
var tempLat = 0;
var tempLon = 0;
for (var i = 0; i < 15000; i++){
tempLat += 1;
tempLon += 1;
if (tempLat > 90){
tempLat = 0;
tempLon = 0;
}
addBillboard(tempLat, tempLon);
}
Sandcastle.finishedLoading();
});

Categories