the following flash actionscript below stores letters and numbers into an array and displays them randomly in a flash movie as "falling text" down the screen. I'd like to modify this script so I can have the array store multiple images verses letters and numbers.
source:
http://www.flashcomponents.net/tutorials/letter_and_number_rain_flash_tutorial/page_1.html
--- layer script
var letter_array = new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","1","2","3","4","5","6","7","8","9","0");
var i = 0;
setInterval(nLetter, 70);
function nLetter()
{
duplicateMovieClip(letterMC, "letter" + i, 10 + i);
i++
}
-------- symbol script
onClipEvent(load)
{
var index = Math.round(Math.random() * _root.letter_array.length - 1)
this.letter.text = _root.letter_array[index];
_x = Math.round(Math.random() * 540) + 5
_y = Math.round(Math.random() * -20) - 10;
var gravity = 0.2;
var ran = Math.round(Math.random() * 50) + 50;
_alpha = ran + 10;
_xscale = _yscale = ran;
speed = Math.round(Math.random() * 5) + 10;
rotSpeed = Math.round(Math.random() * 6) - 3;
//this.letter.textColor = Math.random() * 0xFFFFFF
}
onClipEvent(enterFrame)
{
_y += speed;
_rotation += rotSpeed
speed += gravity;
if(_y > 410)
{
this.removeMovieClip();
}
}
You need to add this at the top of your code:
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.*;
In the layer script you need to have an array of images, so the first thing would be to load all your images and store them in an array when the loading is complete.
in the following code , replace i "inferior to" totalNumImages with
i < totalNumImages , I can't use the "<" character in the code.
//your images location
var url1:String = "images/image1.jpg";
var url2:String = "images/image2.jpg";
var urls:Array = [ url1 , url2 ];
var images:Array = [];
//the total number of images
var totalNumImages:int = 2;
for(var i:int ;i "inferior to" totalNumImages ; ++i )
{
loadImage(images[i] );
}
function loadImage(url:String):void
{
var loader:Loader = new Loader();
var info:LoaderInfo = loader.contentLoaderInfo;
info.addEventListener(Event.COMPLETE , loadComplete );
info.addEventListener(IOErrorEvent.IO_ERROR , errorHandler );
loader.load ( new URLRequest(url ));
}
function errorHandler(event:IOErrorEvent):void
{
trace( event );
}
function loadComplete(event:Event):void
{
//assuming the order doesn't matter
images.push(event.currentTarget.loader.content );
//all images are loaded, let's start...
if(images.length == totalNumImages )
nLetter();
}
After all your images have loaded you can start the nLetter() function. Each time a MovieClip is added to the stage, it will load its image from the array of images that you've created.
change this:
this.letter.text = _root.letter_array[index];
to this:
//assumes that you have an array of DisplayObject
addChild( _root.images[index]);
Related
hi i have an issue with set state , i write the function that i get Position x,y and size of width , height(That is the name of the state that holds them POx1, POY1, widthSize, heightSize) and depend on user choise, i change the state's that user get to me and Use them. but after the first setSate for all these State i can't update and or change them . these are my code's:
function DrawPicture() { // this function call after click
setCountClick(CountClick + 1);
var Se_image = new Image();
Se_image.src = ImgSRC;// (ImgSRC) is the State i define it before
Se_image.onload = function () {
ctxRef.current.globalCompositeOperation = "source-over";
if (CountClick === 2) {// For some reason, I want this condition to be executed after calling the above function twice
var img = Se_image
PictureCategory(img) // This function is shown below
var canvas = canvasRef.current
var ctx = canvas.getContext('2d');
var imageData = ctx.getImageData(POx1, POY1, widthSize, heightSize);
var data = imageData.data;
console.log(lineColor);
const r = parseInt(lineColor.substr(1, 2), 16)
const g = parseInt(lineColor.substr(3, 2), 16)
const b = parseInt(lineColor.substr(5, 2), 16)
var changeColor = function () {
for (var i = 0; i < data.length; i += 4) {
data[i] = r
data[i + 1] = g
data[i + 2] = b
}
ctx.putImageData(imageData, POx1, POY1);
};
changeColor();
setCountClick(1);
setPointer(false);
}
}
}
and this is my PictureCategory() function:
For convenience, I only took one of the modes
function PictureCategory(image) {
switch (PictureTopic) {
case "Girl":
const XG = POx1 - (0.5 * widthSize) < 0 ? 0 : POx1 - (0.5 * widthSize);
const newWidth= 2.4*widthSize;
const newheight= 2.5*widthSize;
setPOx1(XG)
setwidthSize(newWidth)
setheightSize(newheight)
ctxRef.current.clearRect(XG, POY1, newWidth, newheight);
ctxRef.current.drawImage(image, XG, POY1, 2.4 * widthSize, 2.5 * heightSize);
break;
default:
ctxRef.current.drawImage(image, POx1, POY1, widthSize, heightSize);
break;
}
}
i want to change state's with above function please help me !!!
Not sure if it'll fix your issue, but the following has to be done in any case.
It should be
setCountClick(countClick=> countClick + 1);
When state is updated using its previous value, the callback argument of the state setter should be used.
See https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
i know it's not your answer for this question. but you can use this codes for have new value .
I stored the new values in an object and returned them:
function DrawPicture() {
setCountClick(CountClick + 1);
var Se_image = new Image();
Se_image.src = ImgSRC;
Se_image.onload = function () {
ctxRef.current.globalCompositeOperation = "source-over";
if (CountClick === 2) {
var img = Se_image
const Sizes =PictureCategory(img) // you can store new value in valible
var canvas = canvasRef.current
var ctx = canvas.getContext('2d');
var imageData = ctx.getImageData(Sizes[0].x, Sizes[0].y, Sizes[0].width, Sizes[0].height);
var data = imageData.data;
console.log(lineColor);
const r = parseInt(lineColor.substr(1, 2), 16)
const g = parseInt(lineColor.substr(3, 2), 16)
const b = parseInt(lineColor.substr(5, 2), 16)
var changeColor = function () {
for (var i = 0; i < data.length; i += 4) {
data[i] = r
data[i + 1] = g
data[i + 2] = b
}
ctx.putImageData(imageData,Sizes[0].x, Sizes[0].y);
};
changeColor();
setCountClick(1);
setPointer(false);
}
}
}
function PictureCategory(image) {
switch (PictureTopic) {
case "Girl":
const XG = POx1 - (0.5 * widthSize) < 0 ? 0 : POx1 - (0.5 * widthSize);
const newWidth= 2.4*widthSize;
const newheight= 2.5*widthSize;
ctxRef.current.clearRect(XG, POY1, newWidth, newheight);
ctxRef.current.drawImage(image, XG, POY1, 2.4 * widthSize, 2.5 * heightSize);
return[{x: XG,y:POY1,width:newWidth,height:newheight}]
default:
ctxRef.current.drawImage(image, POx1, POY1, widthSize, heightSize);
break;
}
}
I'm trying to create an array of meshes I added to my THREE.JS scene because I used a for-loop with the load() function to create the instances of the meshes, and I wanted to reference them later for the animate() function. The array shows a list of values in the console, but the length shows up as 0 when logged. This is the code I have:
const manager = new THREE.LoadingManager(); //loading manager
const loader = new GLTFLoader(manager);
let pos_arr = []
manager.onLoad = function(e) {
scene.traverse( function (model) {
if (model.isMesh) {
pos_arr.push(model)
}
})
}
let pos = new THREE.Vector3()
//spheres and equators
let ball = new THREE.Mesh();
let equator = new THREE.Mesh()
for (let i = 1; i <= 12; i++) {
let scale = Math.floor(Math.random() * 3) + 1
let pos_x = Math.floor(Math.random() * 10) * 5 - 25
let pos_y = Math.floor(Math.random() * 10) * 5 - 25
let pos_z = Math.floor(Math.random() * 10) * 5 - 25
pos = new THREE.Vector3(pos_x, pos_y, pos_z)
loader.load( './ball.gltf', function ( gltf ) { //load sphere
gltf.scene.traverse(function(model) {
if (model.isMesh) {
model.castShadow = true;
model.material = sphereMaterial;
}
});
ball = gltf.scene
ball.position.set(pos_x, pos_y, pos_z)
ball.scale.set(scale, scale, scale)
scene.add( ball );
}, undefined, function ( error ) {
console.error( error );
} );
loader.load( './equator.gltf', function ( gltf2 ) {
gltf2.scene.traverse(function(model) { //for gltf shadows!
if (model.isMesh) {
model.castShadow = true
model.material = equatorMaterial
}
});
equator = gltf2.scene
equator.position.set(pos_x, pos_y, pos_z)
equator.scale.set(scale, scale, scale)
scene.add( equator )
}, undefined, function ( error ) {
console.error( error )
} );
}
//light
const light = new THREE.AmbientLight( 0xffffff );
scene.add( light );
console.log(pos_arr)
console.log(pos_arr.length)
This is what the console shows:
I got a recommendation that I use the onLoad attribute for the LoadingManager, which I used, but it didn't work. If anyone happens to know a possible solution, it would be greatly appreciated :)
I'm trying to create an array to localstorage containing some gear box values, witch I then need again to do some more calculations with specific array[?].value.
The problem I'm encountering is that the created entry returns only 2 array entries, although all entries are there but the " is at the beginning and then at the second last entry and then before and after the last entry.
These are the values generated.
spd_Dev = ["202.391,172.876,120.451,102.601,85.173,72.664,61.701,52.706,45.116,38.510,32.326,27.407,22.910,19.536,16.585,14.195,12.228","10.401"]
When I used to use a fixed array I've entered it as:
var spd_Dev = [202.391, 172.876, 120.451, 102.601, 85.173, 72.664, 61.701, 52.706, 45.116, 38.510, 32.326, 27.407, 22.910, 19.536, 16.585, 14.195, 12.228, 10.401];
So my question is how to write this values to localstorage and read again from localstorage so that I can use this values as an array.
This is what I'm trying to work.
var D_RatioId = data.truck.make + data.truck.model + "D_Ratio"
var G_RatioId = data.truck.make + data.truck.model + "G_Ratio"
var fGr = data.truck.forwardGears;
var gr = data.truck.displayedGear;
var Rpm = data.truck.engineRpm * 100;
var spd = data.truck.speed;
var T_Dia = 1008.3;
if (localStorage.getItem(G_RatioID) == undefined) {
localStorage.setItem(G_RatioID, '');
var fG_Rat = [localStorage.getItem(G_RatioID)];
} else {
var fG_Rat = [localStorage.getItem(G_RatioID)];
}
var spd_Dev = localStorage.getItem(Spd_DevId);
spd_Dev = spd_Dev ? spd_Dev.split(', ') : [];
if (localStorage.getItem("i") == undefined) {
localStorage.setItem("i", 1);
var i = localStorage.getItem("i");
} else {
var i = localStorage.getItem("i");
}
if (i <= fGr && spd > 0.5) {
if (i <= fGr + 1) {
if (i == gr) {
if (RPM > 1450) {
var G_Ratio = Math.abs(Rpm / D_Ratio * (Math.PI * T_Dia / 1000) * 60 / spd / 1000, 2).toFixed(2);
var spd_D = Math.abs(RPM / (RPM / G_Ratio / D_Ratio * (Math.PI * T_Dia / 1000) * 60 / 1000) * 0.821932).toFixed(3);
fG_Rat.push(G_Ratio);
spd_Dev.push(spd_D);
i++;
localStorage.setItem("i", i);
var G_RatioValue = fG_Rat;
var Spd_DevValue = spd_Dev;
SetG_Ratio(G_RatioID, G_RatioValue);
SetSpd_Dev(Spd_DevId, Spd_DevValue);
localStorage.setItem("spd_Dev", JSON.stringify(Spd_DevValue));
}
}
}
}
function SetG_Ratio(G_RatioID, G_RatioValue) {
localStorage.setItem(G_RatioID, G_RatioValue);
console.log(G_RatioID, G_RatioValue);
}
function SetSpd_Dev(Spd_DevId, Spd_DevValue) {
localStorage.setItem(Spd_DevId, Spd_DevValue.toString());
console.log(Spd_DevId, Spd_DevValue, Spd_DevValue.length);
}
if (spd >= 0) {
var spd_Dev = [localStorage.getItem(Spd_DevId)];
var spD_D = JSON.parse(spd_Dev);
for (i = 1; i < (fGr + 1); i++) { // Some more code dependant on the above results //
why don't you use LSM.js? it will make everything simpler. you can put the array as an array so that it will return the full array only, you will not need to use split(),
https://github.com/kevinj045/LSM_js
var lsm = new LSM("G_RatioID");
var G_RatioValue ["202.391,172.876,120.451,102.601,85.173,72.664,61.701,52.706,45.116,38.510,32.326,27.407,22.910,19.536,16.585,14.195,12.228","10.401"];
lsm.set("G_RatioID",G_RatioValue);
console.log(lsm.get("G_RatioID")); // it will return the full array
I have this code in my simple flash. I want to save name and score in my quiz. My code reference in this website http://www.mollyjameson.com/blog/local-flash-game-leaderboard-tutorial/
I want to make my code in just one actionscript. But I didn't success do it.
var m_FlashCookie = SharedObject.getLocal("LeaderboardExample");
var EntryName:String ="nama kamu";
var EntryScore:String ="nilai";
const NUM_SCORES_SAVED:int = 10;
inputBoxScore.text = EntryScore;
inputBoxName.text = EntryName
var latest_score_object:Object = {
name: EntryName,
score: EntryScore
};
var arr:Array;
arr = m_FlashCookie.data.storedArray
if ( arr == null)
{
arr = new Array();
}
arr.push( latest_score_object );
arr.sortOn("score", Array.NUMERIC | Array.DESCENDING);
if ( arr.length < NUM_SCORES_SAVED )
{
arr.pop();
}
btnSave.addEventListener(MouseEvent.CLICK, saveData);
function saveData(event:Event):void
{
m_FlashCookie.data.arr = arr;
m_FlashCookie.flush();
}
var myHTMLL:String = "";
var total_stored_scores:int = arr.length;
btnLoad.addEventListener(MouseEvent.CLICK, loadData);
function loadData(event:Event):void
{
for (var i:int = 0; i < total_stored_scores; ++i)
{
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var leaderboard_entry:Object = arr[i];
// is this the last score that was just entered last gamestate?
if ( leaderboard_entry == latest_score_object )
{
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ leaderboard_entry.name + " " + leaderboard_entry.score +"</font></b><br>";
}
else
{
myHTMLL += (i+1) + ". "+ leaderboard_entry.name + " " + leaderboard_entry.score +"<br>";
}
}
myHTML.text = myHTMLL;
}
Can anybody help me?
You're saving the array as data.arr but reading the array as data.storedArray. You need to make them the same.
In other words, you've written this:
m_FlashCookie.data.arr = arr;
And when you load:
arr = m_FlashCookie.data.storedArray;
This clearly doesn't make sense: data.storedArray is never set, so it will never have a value, so you will always end up with a new empty array.
You need to use the same property on the shared object data. For example:
m_FlashCookie.data.storedArray = arr;
m_FlashCookie.flush();
Looking at your code, there's a number of other issues:
The latest score is immediately removed because arr.length < NUM_SAVED_SCORES is going to be true from the start, since arr starts out empty, and it then calls arr.pop() which will remove the latest entry that was just added. So the array is always empty.
It adds the score immediately with arr.push(latest_score_object) instead of waiting until the user clicks save, so the value of the input texts don't matter at all -- the saved values will always be "nama kamu" and "nilai".
The following fixes all the issues mentioned:
var leaderboard = SharedObject.getLocal("leaderboard");
const MAX_SAVED_SCORES:int = 10;
inputBoxName.text = "nama kamu";
inputBoxScore.text = "nilai";
var entries:Array = leaderboard.data.entries || [];
var latestEntry:Object;
displayScores();
btnLoad.addEventListener(MouseEvent.CLICK, loadClick);
btnSave.addEventListener(MouseEvent.CLICK, saveClick);
function loadClick(e:MouseEvent):void {
displayScores();
}
function saveClick(e:MouseEvent):void {
saveLatestScore();
displayScores();
}
function saveLatestScore():void {
// create the latest entry based on input texts
latestEntry = {
name: inputBoxName.text,
score: inputBoxScore.text
};
// add the entry and sort by score, highest to lowest
entries.push(latestEntry);
entries.sortOn("score", Array.NUMERIC | Array.DESCENDING);
// if reached the limit, remove lowest score
if (entries.length > MAX_SAVED_SCORES) {
entries.pop();
}
// store new sorted entries to shared object
leaderboard.data.entries = entries;
leaderboard.flush();
}
function displayScores():void {
var myHTMLL:String = "";
for (var i:int = 0; i < entries.length; ++i) {
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var entry:Object = entries[i];
// is this the last score that was just entered last gamestate?
if (entry == latestEntry)
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ entry.name + " " + entry.score +"</font></b><br/>";
else
myHTMLL += (i+1) + ". "+ entry.name + " " + entry.score +"<br/>";
}
myHTML.htmlText = myHTMLL;
}
I'm having this issue with this memory match game. I want the cards to show face up so the user can memorize them, and after 3 seconds I want them to turn over and show their back face.
I got the entire game working perfectly, btw. I'm just missing this detail!
the code below is how my cards get created (they are all 1 movieclip (mcCartas) with 37 frames inside (36 types of card and back card))
const QUANT_CARTAS:int = 36; ///// number of cards (faces drawn, frame numbers)
const CARTAS_POR_LINHA:int = 6; /// number of lines (6x6 grid)
var cartas:Array = new Array(); // cards array
var cartasColetadas:Array = new Array(); // clicked cards array
////////gets the 36 cards into the array
for(var i:int=0;i<QUANT_CARTAS;i++)
{
cartas.push(i);
}
/////////shuffles the cards
for(var moeda:int = QUANT_CARTAS-1;moeda>0;moeda--)
{
var pos:int = Math.floor(Math.random() * moeda);
var carta:int = cartas[moeda];
cartas[moeda] = cartas[pos];
cartas[pos] = carta;
}
////////// puts them on the table
for(i=0;i<QUANT_CARTAS;i++)
{
var novaCarta:Carta = new Carta();
novaCarta.tipoCarta = cartas[i];
novaCarta.x = 5 + (novaCarta.width + 2.7) * (i % CARTAS_POR_LINHA);
novaCarta.y = 5 + (novaCarta.height + 2.7) * (Math.floor(i/CARTAS_POR_LINHA));
novaCarta.gotoAndStop(cartas[i]+1); // this line they all face their number OR
//novaCarta.gotoAndStop(QUANT_CARTAS + 1); // this line they all face back (last frame)
novaCarta.buttonMode = true;
novaCarta.addEventListener(MouseEvent.CLICK, cartaClicada);
addChild(novaCarta);
trace (cartas);
if(i == 35)
{
podeJogar = false;
mcContagem.x = 884;
mcContagem.y = 511;
addChild(mcContagem);
intervalo = setInterval(desviraCartas, 3000);
function desviraCartas()
{
for(var j:int = 0;j < QUANT_CARTAS; j++)
{
//here I'm trying to make them go back to their back (last frame)
//something????.gotoAndStop(QUANT_CARTAS + 1);
if(j == 35)
{
clearInterval(intervalo);
iniciaJogo();
}
}
}
}
}
this code IS working, but a couple lines up where I typed "something????.gotoAndStop etc" ... that's where I have tried everything... heeelppppp plzzzzz
You should store the new Cartas in an array when you add them. Then use that array to reference them: Push into array:
aCartasMCs.push(novaCarta);
Then you can reference like:
aCartasMCs[i].gotoAndStop(QUANT_CARTAS + 1);