Use SKSpriteNode(s) Multiple Times From An Array - arrays

The app I'm working on has multiple nodes which are added repeatedly to the game. What I have been doing is creating new SKSpriteNodes using an array of texture, and once the node has been added, I assign that node with a specific physics body. But what I would like to do is instead of a having an array of textures, have an array of SKSpriteNodes with the physics body pre-assigned.
I believe I have figured out how to do this, the problem I have is when I try to add that SKSpriteNode more then once to the scene.
For example, below is I'm been playing around with, which works, but if I add another line of addChild(arraySegment_Type1[0] as SKSpriteNode), I get an error and the app crashes.
override func didMoveToView(view: SKView) {
anchorPoint = CGPointMake(0.5, 0.5)
var arraySegment_Type1:[SKSpriteNode] = []
var sprite = SKSpriteNode(imageNamed: "myimage")
sprite.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(sprite.size.width, sprite.size.height))
sprite.physicsBody?.dynamic = false
sprite.name = "mysprite"
arraySegment_Type1.append(sprite)
addChild(arraySegment_Type1[0] as SKSpriteNode)
}
Does anybody know how I would be able to load SKSpriteNodes multiple times from an array?

What your code does at the moment is the following:
Creates an empty array of the type [SKSpriteNode]
Creates a single SKSpriteNode instance
Ads a physicsBody to the sprite
Ads this single spriteNode to an array
Picks out the first object in the array (index 0) and ads it to the parentNode.
Your app crashes because you are trying to add the same SKSpriteNode instance to the scene several times over.
Here is a reworked version of your code that actually ads several sprites to the scene, it technically works but does not make a lot of sense just yet:
override func didMoveToView(view: SKView) {
// your ARRAY is not an array-segment it is a collection of sprites
var sprites:[SKSpriteNode] = []
let numberOfSprites = 16 // or any other number you'd like
// Creates 16 instances of a sprite an add them to the sprites array
for __ in 0..<numberOfSprites {
var sprite = SKSpriteNode(imageNamed: "myimage")
sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size)
sprite.physicsBody?.dynamic = false
sprite.name = "mysprite" // not sure what your plans are here...
sprites.append(sprite)
}
// picks out each sprite in the sprites array
for sprite in sprites {
addChild(sprite)
}
}
Now as I said this doesn't make all that much sense. As you've probably noticed the sprites all appear on top of each other for one thing. More importantly, doing this all in the didMoveToView means it makes very little sense going through the whole array-dance, you could simply do the following instead:
override func didMoveToView(view: SKView) {
let numberOfSprites = 16 // or any other number you'd like
for __ in 0..<numberOfSprites {
var sprite = SKSpriteNode(imageNamed: "myimage")
// skipping the physicsBody stuff for now as it is not part of the question
addChild(sprite)
}
}
An improvement obviously, but all sprites are still covering each other, and didMoveToView might not be the best place to handle all this anyway, so perhaps something like this to illustrate the point:
override func didMoveToView(view: SKView) {
let sprites = spritesCollection(count: 16)
for sprite in sprites {
addChild(sprite)
}
}
private func spritesCollection(#count: Int) -> [SKSpriteNode] {
var sprites = [SKSpriteNode]()
for __ in 0..<count {
var sprite = SKSpriteNode(imageNamed: "myimage")
// skipping the physicsBody stuff for now as it is not part of the question
// giving the sprites a random position
let x = CGFloat(arc4random() % UInt32(size.width))
let y = CGFloat(arc4random() % UInt32(size.height))
sprite.position = CGPointMake(x, y)
sprites.append(sprite)
}
return sprites
}
Now, long-wound as this is it is still just a starting point towards a working and more sensible code-structure...

Related

Xcode6 Swift. arc4random using array with textures

I have a spriteNode which has a default texture of a black circle and I have placed it in the center of the screen. I also have an array which contains 4 textures. What I want to do is when I click on the screen the black circle in the center randomly picks a SKTexture from the array and changes into set texture. I was thinking a long the lines of the code in the didBeginTouches but I'm stuck on how to truly execute this idea. Thanks for any help. :)
var array = [SKTexture(imageNamed: "GreenBall"), SKTexture(imageNamed: "RedBall"), SKTexture(imageNamed: "YellowBall"), SKTexture(imageNamed: "BlueBall")]
override func didMoveToView(view: SKView) {
var choiceBallImg = SKTexture(imageNamed: "BlackBall")
choiceBall = SKSpriteNode(texture: choiceBallImg)
choiceBall.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)
self.addChild(choiceBall)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
choiceBall.texture = SKTexture(imageNamed: arc4random(array))
//error: Cannot assign a value of type 'SKTexture!' to a value of type 'SKTexture?'
}
Almost there, change your touchesBegan to this:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
choiceBall.texture = array[randomIndex]
}
First line generates a random number from 0 to the size of your array-1 using the arc4random_uniform function. We also need to convert the size of your array to an Unsigned Integer because Swift is very strict (and rightfully so). We then cast it back to an Integer and use it to access the textures that you already created in your array.

A3 Arrays of movieClips

[AS3.0] I'm currently working on my graduation diploma and I have a problem with managing movieClips with the same instance name..sort of. I'm creating an array of objects with this Class an Arrays in frame 1:
package
{
import flash.display.MovieClip;
public class createFractionBuilding
{
public function createFractionBuilding(_fractionBuildingMovieClip:MovieClip, _fractionBuildingLevel:Number,_fractionBuildingCost:Number, _fractionBuildingFrame:Number)
{
fractionBuildingLevel = _fractionBuildingLevel;
fractionBuildingCost = _fractionBuildingCost;
fractionBuildingMovieClip = _fractionBuildingMovieClip
fractionBuildingFrame = -fractionBuildingFrame
}
public var fractionBuildingLevel:Number,fractionBuildingCost:Number,fractionBuildingFrame:Number;
public var fractionBuildingMovieClip:MovieClip
}
}
On main timeline I'm refering to this Class by creating an Array of objects:
var allHumanBuildingsList:Array = new Array();
var humanCapitolBuildingProperties:createFractionBuilding = new createFractionBuilding(humanCapitol_mc,1,1000,1);
var humanCastleBuildingProperties:createFractionBuilding = new createFractionBuilding(humanCastle_mc,2,1000,1);
allHumanBuildingsList.push(humanCapitolBuildingProperties);
allHumanBuildingsList.push(humanCastleBuildingProperties);
For this to work I have to have movieclip called "humanCapitol_mc" or "humanCastle_mc" in this frame (1).
But in frame (2) I want to refer to this movieClip with such function:
function humanBuildingLevelCheck()
{
for (var a:Number = 0; a < allHumanBuildingsList.length; a++)
{
trace (String(allHumanBuildingsList[a].fractionBuildingMovieClip))
if (allHumanBuildingsList[a].fractionBuildingLevel == 2){
allHumanBuildingsList[a].fractionBuildingMovieClip.gotoAndStop(3)
} else if (allHumanBuildingsList[a].fractionBuildingLevel == 1){
allHumanBuildingsList[a].fractionBuildingMovieClip.gotoAndStop(2)
}
}
}
humanBuildingLevelCheck()
(Each MovieClip on first frame is blank, on second is one picture, on third is different one)
Everything works, when the array creation code is in frame two, but it won't work the way I want: first I create variables and objects and then I change it's values dynamically. Do you have an idea, how could that work?
Make it global. If one variable is declared in keyframe 1, you can't see it in keyframe 2 but if you declare it in one layer that has only one keyframe then it will be visible anywhere within that timeline.

AS3 - MovieClip array: play each movie after another

AS3 Newbie here... very confused, please be kind ;)
I have a MovieClip (rozette), which contains 7 instances of a MovieClip (circle). circle contains an animation and I would like to play each instance of it within rozette consecutively.
Questions - do I need to use an array? Is using eventListener the best way to do this? If so, how can I create an eventlistener for each item in the array? And what kind of event am I listening for?
Many thanks. Kat
You can see some options given as answers here:
Flash AS3 - Wait for MovieClip to complete
Basically I would think you want to have an array and a counter for which one you're on, each time the "playNext" function gets called, you should increment the counter and pull the next movie clip from the array. What this means is the order of elements in the array will dictate the order they play in. Something like:
private var myArray:Array = [mc1,mc2,mc3]; //list all the movieclip instance names here
private var counter:Number = 0; //start off on the first element, arrays in AS3 start at 0
//Play the next clip
private function playNext():void {
//Check that we're not at the end of the list, if so just return/stop
if(counter>myArray.length-1)
return;
//grab the next clip
var curClip:MovieClip = myArray[counter] as MovieClip;
//increment the counter for next time
counter++;
//when the last frame gets hit call this function again
curClip.addFrameScript(curClip.totalFrames-1, playNext);
//play the clip
curClip.play();
}
From your constructor of your Main class you would want to call playNext() once to get things rolling.
import com .greensock.*;
import com. greensock.easing.*;
var s1:b1=new b1();
var s2:b2=new b2();
var s3:b3=new b3();
var r1:Array = new Array();
r1.push(s1);
r1.push(s2);
r1.push(s3);
function ff (){
var i = 0;
while (i < r1.length) {
r1[i].visible=false
r1[0].visible=true
addChild(r1[i]);
i++;
}
TweenMax.staggerTo(r1, 0.4, {visible:true},0.2);
}
bb.addEventListener(MouseEvent.CLICK,cliki4x);
function cliki4x(e:Event):void{
ff ();
}

having issues working with movie clips inside of an array [as3]

In a game I'm making, I'm trying to have sprites put on top of a hit box. The best way I could think of accomplishing this is to make two arrays; one for the hit boxes, and one for the sprites, and then have the sprites stay on top of their respective hit-box via a for loop that will be in its own script.
Problem is, is that when I try to get the MovieClips in either of the arrays to do anything, it doesn't work. If I do a trace on the X or Y location of the sprites, I get "undefined" in my terminal. I'm going to explain this from the top down.
Here is an excerpt from my class that contains the for loop (Dasengine is my main class fyi)
for(var i:Number = 0; i < Dasengine.ovrcnt.length; i++){
trace(Dasengine.ovrcnt[i].x); //returns "undefined"
trace(Dasengine.ovrcnt[i]); //returns "object Onmea"
Dasengine.ovrcnt[i].x = Dasengine.enemycnt[i].x;//this isn't working
}
In another script when an enemy spawns, they go through this method.
if(ENEMY SPAWN CONDITION IS MET ){
Dasengine.baddie = new nme_spawn.Enemya(); //ENEMY HITBOX
Dasengine.Obaddie = new nme_overlay.Onmea(); //ENEMY's sprite
Dasengine.enemycnt[cntup] = [Dasengine.baddie]; //Enemy's Hit box movie clip is put in array meant for holding enemy movie clips
Dasengine.ovrcnt[cntup] = [Dasengine.Obaddie]; //Enemy sprites that go over the hit boxes are stored here
cntup++; //this is so movie clips are put in new parts of the array
}
in my main class, the movie clips are declared as follows also I have the addChild functionality in there.
public static var Obaddie:nme_overlay.Onmea;
//^variable for sprite
public static var baddie:nme_spawn.Enemya;
//^variable for hitbox
also Obaddie= Overlay baddie. Its the MovieClip that acts as what goes on top of the hitbox, this is what the player will see
badde = is simply the hitbox. This contains the "meat" of the enemy ai.
I talked about this with some friends and they thought I might need to define what 'X' is inside of the class of the object that is in the array. So I did the following
package nme_overlay {
import flash.display.*;
import flash.events.*;
import nme_spawn.*;
public class Onmea extends MovieClip{
// Constants:
// Public Properties:
// Private Properties:
public static var xloc:int = 0;
// Initialization:
public function Onmea() {
this.addEventListener(Event.ENTER_FRAME, overlaya);
}
private function overlaya(e:Event){
xloc = 55;
//trace(xloc);
}
}
}
and then for the looping class I did this
for(var i:Number = 0; i < Dasengine.enemycnt.length; i++){
trace(Dasengine.ovrcnt[i]);//returns "object Onmea"
trace(Dasengine.ovrcnt[i].xloc);//still returns "undefined"
}
Your xloc variable is static--it belongs to nme_overlay, the Class, not any particular instance. If you were to do this in your code AND you had strict mode on (which I suspect you do not, because there's a lot of stuff in your code that should be giving you at least warnings), you'd get an error that would tell you exactly that:
for(var i:Number = 0; i < Dasengine.enemycnt.length; i++){
trace(Dasengine.ovrcnt[i]);//returns "object Onmea"
trace(nme_overlay(Dasengine.ovrcnt[i]).xloc);//still returns "undefined"
}

Sprites and Arrays as3

I have a sprite called food which adds to the screen via the use of a timer. more food items are added to the screen over time. How would i hit test all these food sprites with another object?
(the makeItem function creates the sprite btw)
private function placeFood(event:TimerEvent = null):void{
var rndI:uint = Math.floor(Math.random() * DIM); //sets a random integer based on the the floor
var rndJ:uint = Math.floor(Math.random() * DIM);
var rndX:Number = grid[rndI][rndJ].x; // sets a grid position for the food item to go
var rndY:Number = grid[rndI][rndJ].y;
food = makeItem(Math.random() * 0xFFFFFF);// random color
food.x = rndX;
food.y = rndY;
var foodArray:Array = new Array();
foodArray.push(food);
trace(foodArray.length)
addChild(food); //adds the food to the board
for (var i:uint = 0; i < snake.length; i++){
if (rndY == snake[i].y && rndX == snake[i].x){
placeFood();
}
}
}
Add the food items to an array and loop through that array doing hitTestObject. Something like:
var foods:Array = new Array();
foods.push(makeItem(blah));
...
for each (food in foods) {
food.hitTestObject(object);
}
It looks like you're putting items on a fixed grid. Do the food items move around? Your food does not move, and your snake (or whatever collides with the food) does, you can greatly optimize your collision detection by figuring out what grid square(s) the moving object occupies and only checking against food in that local area.
Generally speaking, when you need to do collision detection between many objects, you do it in multiple passes. The first pass would consist of the least computationally expensive checks to cull things that could not possibly be colliding such as objects that are very far apart, moving away from each other, etc. Your next pass might be something like simple boundary box or circle tests. Lastly, when you're down to the few items that pass all the cheap tests, you can use more expensive and accurate hit tests like pixel-by-pixel ones between hit masks.
Another way avoiding arrays is to use a sprite that contains all food. Every sprite is a collection of sprites and therefore a tree. That's what I use for hit detection: 1 special sprite contains only enemies / food. Run through all children and you don't even need to check the types of them. Cast them if needed.
// begin
var foodCollection: Sprite = new Sprite();
// time passes, food is added
foodCollection.addChild(food);
// hit test
for (var i:int = 0; i < foodCollection.NumChildren; i++)
{
var food: Sprite = foodCollection.getChildAt(i);
// test
}

Resources