so this is my first time here. Have looked around if this question has been answered, and it has, but not clear enough for me. Sorry for the potential double post.
I am trying to get enemies on the screen. They spawn at random positions, as you can see below, but... they spawn on top of their previous spawned enemy. The answers I read include putting it into an array, but I did, right? I'm a bit confused and working on this for too long, might be that too.
Thanks in advance!
function enemySpawn(e:TimerEvent) {
var enemyAxis:int = Math.round(Math.random()); // determines the x or y axis (0 or 1)
var enemyPos1:int = Math.round(Math.random()) * 600; // spawning it outside the stage (0 or 600)
var enemyPos2:int = Math.floor(Math.random() * 600); // spawning it at random around the stage border (0 through 600)
// spawning the enemy at correct axis
addChild(_enemy);
if(enemyAxis == 0){
// we declare 0 = x-axis, then either position 0 or max-width, plus the enemy's width.
_enemy.x = enemyPos1;
_enemy.y = enemyPos2;
} else
if(enemyAxis == 1){
// we declare 1 = y-axis, then either position 0 or max-height, plus the enemy's height.
_enemy.y = enemyPos1;
_enemy.x = enemyPos2;
}
enemyContainer.push(_enemy);
Not sure that I understood you correctly, but calling addChild is not enough to create a new instance of MovieClip. It just adds it to the target container (or does nothing, if the MC is already in that container).
If you want to spawn several enemies simultaneously, you should create new instances of your MC using the new keyword prior to calling addChild:
var enemy:MovieClip = new Enemy();
addChild(enemy);
// _enemies is an array/vector that contains all created enemies;
// it is not necessary, but helps to access the enemy later, when
// the call of enemySpawn() function inside which the enemy was created
// has ended
_enemies.push(enemy);
To be able to do this, you'll need to enable AS3 linkage for the Enemy symbol in the Library. See this answer.
Related
Trying to draw multiple objects in WebGL.
Each object has its own data. I use loop to draw each object at a time. And WebGL shows only the last object. When I try to draw them separately from each other (click one time - the first one is drawn, click second time - then the next object drawn over the first one) everything is fine. Is it possible to use multiple draw-calls for separate object in a loop and to get one combined image?
PS: I dont use 'clear' functions inside the loop.
Here is some code.
Object structure:
let someObject = {
// Program to execute
program: program,
// Vertex buffer
buffer: positionBuffer,
// Vertex attribute location
attribLocation: positionAttributeLocation,
// Data per primitive
count: positions.length / 2, // 2 values per vertex: X, Y
// Uniforms
// [{type, vareableLocation, valueToPass}, ...]
uniforms: updateObjectUniforms(program)
};
Drawing loop-call
for (let i = 0; i < objectsToDraw.length; i++) {
drawObject(objectsToDraw[i]);
}
I use gl.darwArrays function
function drawObject(object) {
var programInfo = object.programInfo;
var bufferInfo = object.bufferInfo;
gl.useProgram(programInfo.program);
// Setup all the needed attributes
// Bind buffers
...
// Upload uniforms
...
// Draw
gl.drawArrays(gl.TRIANGLES, 0, bufferInfo.numElements);
});
Has anyone been able to loop a MIDI file without problems on IOS9 Beta?
As soon as I try to loop by setting numberOfLoops to 0 in MusicTrackLoopInfo, it locks up the app by sending random MIDI to the player. I've reported it, but am wondering if anyone has found a work around. The same code works perfectly under all other iOS versions.
MusicTrackLoopInfo loopInfo;
loopInfo.loopDuration = loopLength;
loopInfo.numberOfLoops = 0;
OK I just heard iOS9 will ship with this bug in it. Terrible.
Here is a work around.
Don't set numberOfLoops at all, OR set numberOfLoops = 1; // means loop once
Now make a variable (i.e. myVariableToKeepTrackOfAddedCopies) that keeps track of the number of times you will actually perform the following:
In your MIDIReadProc at some point BEFORE the track has finished playing, do the following:
// Copy the track to itself - effectively doubling the length
MusicTrack theTrack=nil;
MusicTrackGetProperty(theTrack, kSequenceTrackProperty_TrackLength, &trackLen, &trackLenLen);
trackLen = 4.0; //<-- this is your real track length
MusicTrackCopyInsert(theTrack, 0, trackLen, theTrack, 0);
myVariableToKeepTrackOfAddedCopies++;
So now your track is twice as long before it ends and the track will continue. This will work the same as looping except you are taking up more memory since you are making the track length longer after each iteration.
When you stop the sequence/track, cut the track back to the original size.
MusicTrackCut(theTrack, 4.0, 4.0 + (4.0*myVariableToKeepTrackOfAddedCopies));
MusicTrackGetProperty(theTrack, kSequenceTrackProperty_TrackLength, &trackLen, &trackLenLen);
Irritating, but it works. I just verified on iOS9 beta 5. Hope it helps.
This is fixed as of iOS release 9.2
Oddly enough, the tempo track does not seem to have this problem. The following code does not lock up for me:
MusicTrack tempoTrack;
OSSTATUS = MusicSequenceGetTempoTrack(self.sequence, &tempoTrack);
SafeMusicTrackClear(tempoTrack); //calls into MusicTrackClear
MusicTrackNewExtendedTempoEvent(tempoTrack, 0, self.tempo * self.tempoMultiplier);
MIDIMetaEvent timeSignatureMetaEvent;
timeSignatureMetaEvent.metaEventType = 0x58;
timeSignatureMetaEvent.dataLength = 4;
timeSignatureMetaEvent.data[0] = 1;
timeSignatureMetaEvent.data[1] = 4;
timeSignatureMetaEvent.data[2] = 0x18;
timeSignatureMetaEvent.data[3] = 0x08;
MusicTrackNewMetaEvent(tempoTrack, 0, &timeSignatureMetaEvent);
MusicTrackLoopInfo loopInfo;
loopInfo.loopDuration = 0.25f;
loopInfo.numberOfLoops = 0;
MusicTrackSetProperty(tempoTrack, kSequenceTrackProperty_LoopInfo, &loopInfo, sizeof(loopInfo));
Unfortunately, it does not seem that the tempo track can actually play notes.
UPDATE:
After a few hours of digging around and trying to figure out a better solution to the problem, I settled on manually looping by sending a user event at the end of my sequence.
My sequence is created in a method...
-(void) loadPacketsForLoopingSequence {
SafeMusicTrackClear(loopingTrack); //calls into MusicTrackClear
// calculate timestampToPlaySequenceAt -- the starting point of the current sequence iteration, probably in the past, based on MusicPlayerGetTime and the length of the sequence -- here
// calculate timestampToPlayNextSequenceAt -- the starting point of the next sequence iteration, based on MusicPlayerGetTime and the length of the sequence -- here
// a single iteration of the notes get added to loopingTrack here, starting at timestampToPlaySequenceAt
MusicEventUserData event;
event.length = 1;
event.data[0] = 0xab; //arbitrary designation
// -0.5 to make sure we still have time to do the next step in the callback
MusicTrackNewUserEvent(loopingTrack, timestampToPlayNextSequenceAt - 0.5, &event);
}
...which is called again in the callback:
void sequenceCallback(void* inClientData,
MusicSequence inSequence,
MusicTrack inTrack,
MusicTimeStamp inEventTime,
const MusicEventUserData* inEventData,
MusicTimeStamp inStartSliceBeat,
MusicTimeStamp inEndSliceBeat) {
CSMidiMusicPlayer* musicPlayer = (CSMidiMusicPlayer*)inClientData;
[musicPlayer loadPacketsForLoopingSequence];
}
The callback has to be registered during sequence init using MusicSequenceSetUserCallback.
The -0.5 kludge could probably be eliminated altogether by examining the parameters in sequenceCallback and modifying loadPacketsForLoopingSequence to accept a parameter, but I haven't gotten that far yet.
I like this solution because it stays in MIDI time and doesn't modify the MIDI file in unexpected, stateful ways. (New notes basically get streamed in when you get close enough to a loop marker.)
Ok, so I have some experience with as3 and some of the basics. But this problem has been stumping me for so long. I tried to do a workaround based on what I currently know about as3. But somehow either i get an error message or it just doesn't do anything at all. Here is the code that i'm trying to solve.
var zombieCount:Array = new Array();
var helltime:Timer = new Timer(1500);
helltime.addEventListener(TimerEvent.TIMER, spawnzombies)
helltime.start();
function spawnzombies(happened:TimerEvent){
var zombie1:Zombie = new Zombie();
zombieCount.push(zombie1);
stage.addChild(zombieCount[zombieCount.length - 1]);
zombie1.x = 135 + (330*Math.random())
zombie1.y = -29
stage.addEventListener(Event.ENTER_FRAME, move_zombie)
function move_zombie(happened:Event){
for(var i:int; i < zombieCount.length; i++){
zombieCount[i].y = zombieCount[i].y + 1;
if(zombieCount[i].hitTestObject(border)){
stage.removeChild(zombieCount[i]);
zombieCount.shift();
trace(zombieCount.length);
}
}
}
}
While this may not be inclusive of everything wrong, here are at least a few of the issues I see.
Inline function issue:
Inside your timer tick handler (spawnZombies), you create an inline function called move_zombie and then add an enter frame handler that calls that function.
The issue here, is that every tick of the timer, will then create a whole new copy of that function, and add ANOTHER enter frame handler. This will create huge problems after a few timer ticks.
Break that move_zombie function OUT OF the spawn function:
eg:
helltime.addEventListener(TimerEvent.TIMER, spawnzombies)
helltime.start();
stage.addEventListener(Event.ENTER_FRAME, move_zombie);
function move_zombie(......
function spawnzombies(.....
Iteration issue:
In your for loop:
for(var i:int; i < zombieCount.length; i++){
zombieCount[i].y = zombieCount[i].y + 1;
if(zombieCount[i].hitTestObject(border)){
stage.removeChild(zombieCount[i]);
zombieCount.shift();
trace(zombieCount.length);
}
}
You are not initializing your i value. While this will default it to 0, it's still a good idea for readability to initialize it.
So your iterating forward from 0 to the end of the array. However, if your hit test succeeds, you then use the shift method of the array. This removes the first item of the array (irrespective of what value i is at the time). This will remove the wrong item, plus mess up what zombieCount[i] refers to (because the amount of items has now changed after doing shift, so the next iteration zombieCount[i] will be a reference to same item as the previous iteration).
Instead of what you're currently doing, use the splice method to remove, and iterate backwards so your index doesn't get out of whack.
for(var i:int=zombieCount.length-1;i >=0;i--){
zombieCount[i].y += 1; //move it down 1 pixel
if(zombieCount[i].hitTestObject(border)){
stage.removeChild(zombieCount[i]);
zombieCount.splice(i,1); //remove the item at the current index (do this instead of shift)
trace(zombieCount.length);
}
}
I'm writing a game with Flash CS5/AS 3.0 that tries to simulate depth of field by drawing all the relevant Movie Clips based on their Y position in ascending order, i.e. things lower on the stage overlap things higher on the stage. A MovieClip with a Y position of 10 would therefore need to have a lower index compared to a MovieClip with a Y position of 20, so the second one gets drawn on top of the first.
I wrote a quick and dirty function just to test this. During the trace, I've noticed that the truck's index hits 0 when I go near the top of the stage, but if I go too far up it will completely disappear from the stage. Trace then starts generating this error:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/getChildIndex()
at EICT::Game/ReorganizeDisplayIndexes()
at EICT::Game/loop()
theTruck is a MovieClip of the player controlled vehicle
Enemies, Cones, Rocks are all arrays which contain MovieClips
None of them have event listeners.
private function ReorganizeDisplayIndexes(): void
{
var drawableObjects:Array = new Array();
drawableObjects.push(theTruck);
drawableObjects = drawableObjects.concat(Enemies, Rocks, Bushes);
drawableObjects.sortOn("y", Array.DESCENDING | Array.NUMERIC);
drawableObjects.reverse();
trace(collisionLayer.getChildIndex(theTruck));
for (var a:int = collisionLayer.numChildren - 1; a >= 0; a--)
{
collisionLayer.removeChildAt(a);
}
for (var i:int = 0; i < drawableObjects.length; i++)
{
collisionLayer.addChild(drawableObjects[i]);
}
}
Hint: You don't need to remove the child first. When you use addChild() on an object, it is automatically re-added to the next highest depth.
That said, you'll just need to do something like this:
drawableObjects.sortOn("y");
for each(var i:DisplayObject in drawableObjects)
{
if(i.parent)
i.parent.addChild(i);
}
Use setChildIndex instead of removing and re-adding:
for (var a:int = collisionLayer.numChildren - 1; i >= 0; i--)
{
collisionLayer.setChildIndex(drawableObjects[i], i);
}
Also, it's a bit wasteful to first order the sort in descending and then reversing the array. Sort it ascending to begin with!
I had a hard time trying to word my question properly, so i'm sorry if it seems confusing. Also i'm using the flixel library in flash builder. It may not be that important butcause probably anyone that knows a little more than me or even a little AS3 could probably see what i'm doing wrong.
Anyway, what i'm trying to do is basically create 10 instances of this square object I made. all I have to do is pass it an x an y coordinate to place it and it works. so ive tested if i just do:
var testsquare:Bgsq;
testsquare = new Bgsq(0,0);
add(testsquare);
it works fine and adds a square at 0,0 just like i told it to, but i want to add 10 of them then move the next one that's created 25 px to the right (because each square is 25px)
my problem is that I only ever see 1 square, like it's only making 1 instance of it still.
anyone possibly have an idea what I could be doing wrong?
var counter:int = 0;
var bgsqa:Array = new Array;
for (var ibgs:int = 0; ibgs < 10; ibgs++)
{
bgsqa[counter] = new Bgsq(0,0);
bgsqa[counter].x += 25;
add(bgsqa[counter]);
counter++;
}
There's a lot you're doing wrong here.
First off, you're using a pseudo-iterator (counter) to access array elements through a loop instead of, well, using the iterator (ibgs).
Second, I don't see anything in the array (bgsqa) you're iterating through. It's no wonder you're having problems. Here's what you should do.
var bgsqa:Array = [];
for(var i:int=0;i<10;i++)
{
var bgsq:Bgsq = new Bgsq(i * 25, 0);
add(bgsq);
bgsqa.push(bgsq);
}
That should probably do it if your post is accurate.
for (var ibgs:int = 0; ibgs < 10; ibgs++)
{
bgsqa[counter] = new Bgsq(0,0);
bgsqa[counter].x = counter * 25;
add(bgsqa[counter]);
counter++;
}
They start at 0, so applying += is simply adding 25 to 0. This should do the trick.