actionscript-3 - length - as3 0 soundchannel
'파일'을 사용하여 장면 객체 위치를 저장하여 AS3에서 나중에 다시 빌드합니다. (4)
var bytes:ByteStream;
var filename:String = "mySaveFile.sav";
//[...] //initialize byte stream with your data
//get a reference to where you want to save the file
//(in this example, in the application storage directory,
//which is fine if you don't need to move the save file between computers
var outFile:File = File.applicationStorageDirectory;
outFile = outFile.resolvePath(fileName);
//create a file output stream, which writes the byte stream to the file
var outStream:FileStream = new FileStream();
outStream.open(outFile, FileMode.WRITE);
outStream.writeBytes(bytes, 0, bytes.length);
outStream.close();
//to load the file:
var inFile:File = File.applicationStorageDirectory;
inFile = inFile.resolvePath(fileName);
bytes = new ByteArray();
var inStream:FileStream = new FileStream();
inStream.open(inFile, FileMode.READ);
inStream.readBytes(bytes);
inStream.close();
ActionScript 3의 'File'함수를 사용하여 다음 정보를 저장하려고합니다.
장면에서 드래그 가능한 표시 객체를 다양하게 만들 수 있습니다. 금액과 유형이 다를 수 있습니다. 금액과 위치를 저장 한 다음 향후 세션에서 다시로드하려고합니다.
File을 사용하여 저장하는 데 어려움을 겪고 있습니다. Adobe 문서를 검색하여 사용 방법을 고민 할 필요가 없습니다.
나는 그것을 사용하는 코드를 아직 개발하지 않았다.
어떤 도움을 주시면 감사하겠습니다.
고맙습니다.
보통 SharedObject를 위치, 배율, 회전 등의 객체 수를 배열 (보통 다차원 배열)로 저장하여 사용합니다.
이 예제는 테스트되었습니다.
먼저 ActionScript Linkage에서 이름으로 "mc"라는 이름의 무비 클립을 만들고 원하는 그래픽을 추가합니다 (이 MovieClip은 나중에 저장할 객체가 될 것입니다). 다음 스크립트를 추가합니다
////////// get random values for each object
var speed:Number ;
var yPosition:Number ;
var size:Number ;
this.width = size;
this.height = size;
this.y = yPosition ;
//// Moving the MovieClip from Left to right
function moving(e:Event):void
{
this.x += speed ;
if(this.x > 550)
{
this.removeEventListener(Event.ENTER_FRAME,moving);
MovieClip(parent).removeChild(this);
}
}
this.addEventListener(Event.ENTER_FRAME,moving);
프로젝트의 루트 단계에서 다음을 추가합니다.
import flash.events.MouseEvent;
import flash.display.MovieClip;
var num:int = 0 ;
var mmc:MovieClip ;
var mySharedObj:SharedObject = SharedObject.getLocal("SavingStatus"); //// SharedObject to save info
function init()
{
if (!mySharedObj.data.savedArray)
{
///// first run No datat saved
this.addEventListener(Event.ENTER_FRAME,addingmcs)
}else {
///// Laoding previusly saved data
loading();
}
}
init() ;
/////////////// adding MovieClips to stage /////
function addingmcs(e:Event):void
{
num +=1 ;
if(num > 20){
num = 0 ;
mmc = new mc ;
mmc.speed = 2 + (5 * Math.random()) ;
mmc.yPosition = 500 * Math.random() ;
mmc.size = 50 + 10 * Math.random() ;
this.addChild(mmc);
}
}
///////////////////////////////////////////
///////////////////////////////////////////////
var obj:* ; //// to hold children MovieClips of the stage
var savingArr:Array = new Array ; //// the array to be saved , Contains all info of the children
////////////// Save all MovieClips with their parameters ////////////
function saving(e:MouseEvent):void
{
this.removeEventListener(Event.ENTER_FRAME,addingmcs)
for (var i:int=0;i<this.numChildren;i++)
{
if (this.getChildAt(i)is MovieClip) { ///// add all MovieClips of the stage to the array with their info (position - size - speed ... etc)
obj = this.getChildAt(i);
savingArr.push([obj , obj.x , obj.y , obj.speed , obj.size]); //// add the info in 3 dimentional array
obj.speed = 0 ;
}
}
////////////////saving array externally
mySharedObj.data.savedArray = savingArr ;
mySharedObj.flush ();
}
save_btn.addEventListener(MouseEvent.CLICK,saving)
////////////// Load all saved parameters ////////////
load_btn.addEventListener(MouseEvent.CLICK,loading)
function loading(e:MouseEvent =null):void
{
savingArr = mySharedObj.data.savedArray ;
for (var i:int=0;i<savingArr.length ; i++)
{
mmc = new mc ;
mmc.x = savingArr[i][1] ; ///// Get saved x
mmc.yPosition = savingArr[i][2] ; ///// Get saved y
mmc.speed = savingArr[i][3] ; ///// Get saved speed
mmc.size = savingArr[i][4] ; ///// Get saved size
addChild(mmc);
}
this.addEventListener(Event.ENTER_FRAME,addingmcs) ;
}
DisplayObject
를 파일에 직접 작성하려고 시도하는 중입니다. Flash가 모든 객체의 기본 직렬화를 처리하는 방식으로 인해 Flash Engine이이를 방지합니다. DisplayObject
를 외부 리소스에 저장하려면 해당 개체의 클래스 및 저장하려는 모든 개체 클래스에 IExternalizable
을 사용해야합니다. writeExternal
의 구현은 상기 객체를 처음부터 다시 만드는 데 필요한 모든 데이터를 저장해야하며, readExternal
은 또한 중첩 된 표시 객체에 대해 addChild()
를 수행하거나 객체가 가질 수있는 다른 내부 구조에 추가하여 해당 DisplayObject
의 무결성을 복원하는 메소드를 사용해야합니다. 있다.
다른 답변에는 XML 또는 JSON을 사용하여 사용자 지정 직렬화를 수행하는 데 필요한 유효 지점이 포함되어 있으며 가져 오기가 필요한 링크가 포함되어 있습니다. 특히 flash.utils.registerClassAlias
및 flash.utils.getDefinitionByName
은 직렬화 된 데이터에서 구조를 다시 만드는 데 필요합니다. 큰 덩어리.
예 : Board
클래스에 드로잉 보드가 있고 마우스를 사용하여 드래그 할 수있는 크기와 색상이 다른 사각형 세트가 있다고 가정 해 봅시다. 사각형은 사용자 정의 된 MovieClip
이며 자체 클래스는 없지만 각 MovieClip
에는 color
속성이 지정되어 구분이 간단합니다. 즉, Board
클래스에서만 IExternalizable
을 구현해야합니다. Board
클래스가 중첩 된 사각형에 대한 모든 링크를 포함하는 pieces
배열을 가지고 있다고 가정하고, 매개 변수로 제공된 너비, 높이 및 색상을 기반으로 적절한 크기의 새 사각형을 만드는 방법을 가정 해 보겠습니다. ( Board
의 데이터 구조에 대한 더 많은 요구 사항이있을 수 있으므로 자세히 살펴보십시오.) 따라서 Board
를 직렬화하는 과정은 중첩 된 MC의 모든 데이터를 수집하여 IDataOutput
에 순서대로 채우는 것입니다. Board
의 인스턴스를 복구하는 프로세스는 저장된 데이터를 검색하고, 어디에 있는지 찾아 분석하고, 저장된 중첩 된 MC를 생성하고, 올바르게 배치하고, addChild() to self and rebuild the
조각을 addChild() to self and rebuild the
.
public class Board extends Sprite implements IExternalizable {
private var pieces:Array;
public function createRectangle(_width:Number,_height:Number,color:uint):MovieClip {
var mc:MovieClip=new MovieClip();
mc.graphics.beginFill(color);
mc.graphics.drawRect(0,0,_width,_height);
mc.graphics.endFill();
mc.color=color;
pieces.push(mc);
return mc;
}
데이터 구조의 미세 조정이 이미 표시되어 있습니다. 전달 된 _width
및 _height
를 MC에 저장할 필요가 있습니다. MC의 실제 width
가 기본 선 두께 (양쪽 모두 1, 0.5)만큼 다를 것이기 때문입니다. x
와 y
는 MC의 속성에서 적절히 검색됩니다. 따라서 두 줄을 모두 createRectangle
추가해야합니다.
mc._width=_width;
mc._height=_height;
이를 통해 Board
직렬화하는 것이 더 쉬워집니다.
public function writeExternal(output:IDataOutput):void {
var pl:int=pieces.length; // cache
output.writeInt(pl); // assuming we keep this array in integral state
for (var i:int=0;i<pl;i++) {
var _mc:MovieClip=pieces[i];
output.writeDouble(_mc.x); // this is usually not rounded when dragging, so saving as double
output.writeDouble(_mc.y);
output.writeDouble(_mc._width);
output.writeDouble(_mc._height);
output.writeInt(_mc._color);
}
// if anything is left about the "Board" itself, write it here
// I'm assuming nothing is required to save
}
복원하려면 IDataInput
에서 writeExternal
으로 작성된 순서와 동일한 순서로 데이터를 읽은 다음 저장 한 표시 목록을 다시 작성해야합니다.
public function readExternal(input:IDataInput):void {
// by the time this is called, the constructor has been processed
// so "pieces" should already be an instantiated variable (empty array)
var l:int;
var _x:Number;
var _y:Number;
var _width:Number;
var _height:Number;
var _color:uint;
// ^ these are buffers to read data to. We don't yet have objects to read these into
input.readInt(l); // get pieces length
for (var i:int=0;i<l;i++) {
input.readDouble(_x);
input.readDouble(_y);
input.readDouble(_width);
input.readDouble(_height);
input.readInt(_color);
// okay we got all the data representing the rectangle, now make one
var mc:MovieClip=createRectangle(_width,_height,_color);
mc.x=_x;
mc.y=_y;
addChild(mc); // createRectangle does NOT have addchild call
// probably because there are layers for the parts to be added to
// I'm assuming there are no layers here, but you might have some!
// pieces array is populated inside createRectangle, so we leave it alone
}
// read all the data you have stored after storing pieces
}
중첩 된 MC에 IExternalizable
을 구현하는 클래스가있는 경우 전체 배열을 writeObject(pieces)
한 명령으로 저장할 수 있습니다. 그러면 플래시가 배열을 통과하여 포함 된 모든 데이터를 찾고 중첩 된 객체에서 writeObject
를 호출합니다 , 본질적으로 해당 클래스의 writeExternal
함수를 배열의 각 인스턴스에 대해 호출합니다. 이러한 배열을 복원하려면 배열을 보면서 표시 목록을 다시 작성하고 각 복원 된 인스턴스에서 addChild()
를 호출해야합니다.
마지막으로 registerClassAlias()
를 호출하여 사용자 정의 객체의 직렬화 또는 비 직렬화를 수행하기 전에 호출해야합니다. 이것들을 호출하는 가장 좋은 장소는 아마도 여러분의 메인 객체 생성자 일 것이다. 이것은 여러분의 응용 프로그램에 포함 된 다른 코드보다 먼저 호출되기 때문이다.
당신은 이미 여기에 약간의 해답을 가지고 있습니다. 그러나 당신의 질문에서, 당신은 아마도 더 큰 맥락을 놓치고 있습니다.
따라서 File
클래스는 디스크의 파일 경로를 나타내며 FileStream
클래스는 해당 파일에 대한 데이터 읽기 및 쓰기를 가능하게합니다. 이들은 사용하기 쉽고 많은 예가 웹에 있습니다. Adobe의 자습서는 다음과 같습니다. 파일 읽기 및 쓰기
그러나 작성할 데이터는 무엇이며 형식 및 데이터 유형은 무엇입니까? 그것들은 더 중요하고 흥미로운 질문입니다.
가장 간단한 방법은 원하는 Sprites
(또는 다른 객체)의 속성을 읽고 쓰는 XML
또는 JSON
과 같은 text
기반 형식을 사용하는 것입니다. 이 파일의 한 가지 장점은 결과 파일이 사람이 읽고 편집 할 수있는 텍스트 파일이라는 점입니다. 간단한 단점은 저장하고 복원 할 속성을 지정하고 간단한 데이터 유형 변환 (문자열을 int로 등)을 처리해야한다는 것입니다.
보다 강력한 접근 방법은 전체 객체의 상태가 저장되고 복원되는 곳에서 Serialization
를 사용하는 것입니다. 이것은 더 복잡하고 어렵지는 않지만 프로젝트 요구에 과도한 부담이 될 수 있습니다. 여기서 좋은 예와 토론이 여기 , 여기 있습니다 .
현재 프로젝트 및 기술 수준에 대해서는 XML
또는 JSON
사용하는 것이 좋습니다. 다음은 XML을 사용하는 자습서입니다. 외부 XML 파일로드 및 처리