Search Results

Search found 471 results on 19 pages for 'addchild'.

Page 5/19 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Cocos2d score resetting is messing up (long post warning)

    - by Jhon Doe
    The score is not resetting right at all,I am trying to make a high score counter where every time you passed previous high score it will update.However, right now it is resetting during the game. For example if I had high score of 2 during the game it will take 3 points just to put it up to 3 as high score instead of keep going up until it is game over. I have came to the conclusion that I need to reset it in gameoverlayer so it won't reset during game. I have been trying to to do this but no luck. hello world ./h #import "cocos2d.h" // HelloWorldLayer @interface HelloWorldLayer : CCLayer { int _score; int _oldScore; CCLabelTTF *_scoreLabel; } @property (nonatomic, assign) CCLabelTTF *scoreLabel; hello world init ./m _score = [[NSUserDefaults standardUserDefaults] integerForKey:@"score"]; _oldScore = -1; self.scoreLabel = [CCLabelTTF labelWithString:@"" dimensions:CGSizeMake(100, 50) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:32]; _scoreLabel.position = ccp(winSize.width - _scoreLabel.contentSize.width, _scoreLabel.contentSize.height); _scoreLabel.color = ccc3(255,0,0); [self addChild:_scoreLabel z:1]; hello world implement ./m - (void)update:(ccTime)dt { NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init]; CGRect projectileRect = CGRectMake( projectile.position.x - (projectile.contentSize.width/2), projectile.position.y - (projectile.contentSize.height/2), projectile.contentSize.width, projectile.contentSize.height); BOOL monsterHit = FALSE; NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init]; for (CCSprite *target in _targets) { CGRect targetRect = CGRectMake( target.position.x - (target.contentSize.width/2), target.position.y - (target.contentSize.height/2), target.contentSize.width, target.contentSize.height); if (CGRectIntersectsRect(projectileRect, targetRect)) { CCParticleFire* explosion = [[CCParticleFire alloc] initWithTotalParticles:200]; explosion.texture =[[CCTextureCache sharedTextureCache] addImage:@"sun.png"]; explosion.autoRemoveOnFinish = YES; explosion.startSize = 20.0f; explosion.speed = 70.0f; explosion.anchorPoint = ccp(0.5f,0.5f); explosion.position = target.position; explosion.duration = 1.0f; [self addChild:explosion z:11]; [explosion release]; monsterHit = TRUE; Monster *monster = (Monster *)target; monster.hp--; if (monster.hp <= 0) { [targetsToDelete addObject:target]; [[SimpleAudioEngine sharedEngine] playEffect:@"splash.wav"]; _score ++; } break; } } for (CCSprite *target in targetsToDelete) { [_targets removeObject:target]; [self removeChild:target cleanup:YES]; } if (targetsToDelete.count > 0) { [ projectilesToDelete addObject:projectile]; } [targetsToDelete release]; if (_score > _oldScore) { _oldScore = _score; [_scoreLabel setString:[NSString stringWithFormat:@"score%d", _score]]; [[NSUserDefaults standardUserDefaults] setInteger:_oldScore forKey:@"score"]; _score = 0; } } - (void)update:(ccTime)dt { NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init]; CGRect projectileRect = CGRectMake( projectile.position.x - (projectile.contentSize.width/2), projectile.position.y - (projectile.contentSize.height/2), projectile.contentSize.width, projectile.contentSize.height); BOOL monsterHit = FALSE; NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init]; for (CCSprite *target in _targets) { CGRect targetRect = CGRectMake( target.position.x - (target.contentSize.width/2), target.position.y - (target.contentSize.height/2), target.contentSize.width, target.contentSize.height); if (CGRectIntersectsRect(projectileRect, targetRect)) { CCParticleFire* explosion = [[CCParticleFire alloc] initWithTotalParticles:200]; explosion.texture =[[CCTextureCache sharedTextureCache] addImage:@"sun.png"]; explosion.autoRemoveOnFinish = YES; explosion.startSize = 20.0f; explosion.speed = 70.0f; explosion.anchorPoint = ccp(0.5f,0.5f); explosion.position = target.position; explosion.duration = 1.0f; [self addChild:explosion z:11]; [explosion release]; monsterHit = TRUE; Monster *monster = (Monster *)target; monster.hp--; if (monster.hp <= 0) { [targetsToDelete addObject:target]; [[SimpleAudioEngine sharedEngine] playEffect:@"splash.wav"]; _score ++; } break; } } for (CCSprite *target in targetsToDelete) { [_targets removeObject:target]; [self removeChild:target cleanup:YES]; } if (targetsToDelete.count > 0) { [projectilesToDelete addObject:projectile]; } [targetsToDelete release]; if (_score > _oldScore) { _oldScore = _score; [_scoreLabel setString:[NSString stringWithFormat:@"score%d", _score]]; [[NSUserDefaults standardUserDefaults] setInteger:_oldScore forKey:@"score"]; _score = 0; } The game overlayer .h file game over @interface GameOverLayer : CCLayerColor { CCLabelTTF *_label; CCSprite * background; int _score; int _oldScore; } @property (nonatomic, retain) CCLabelTTF *label; @end @interface GameOverScene : CCScene { GameOverLayer *_layer; } @property (nonatomic, retain) GameOverLayer *layer; @end .m file gameover #import "GameOverLayer.h" #import "HelloWorldLayer.h" #import "MainMenuScene.h" @implementation GameOverScene @synthesize layer = _layer; - (id)init { if ((self = [super init])) { self.layer = [GameOverLayer node]; [self addChild:_layer]; } return self; } - (void)dealloc { [_layer release]; _layer = nil; [super dealloc]; } @end @implementation GameOverLayer @synthesize label = _label; -(id) init { if( (self=[super initWithColor:ccc4(0,0,0,0)] )) { CGSize winSize = [[CCDirector sharedDirector] winSize]; self.label = [CCLabelTTF labelWithString:@"" fontName:@"Arial" fontSize:32]; _label.color = ccc3(225,0,0); _label.position = ccp(winSize.width/2, winSize.height/2); [self addChild:_label]; [self runAction:[CCSequence actions: [CCDelayTime actionWithDuration:3], [CCCallFunc actionWithTarget:self selector:@selector(gameOverDone)], nil]]; _score=0; }

    Read the article

  • Using Event Driven Programming in games, when is it beneficial?

    - by Arthur Wulf White
    I am learning ActionScript 3 and I see the Event flow adheres to the W3C recommendations. From what I learned events can only be captured by the dispatcher unless, the listener capturing the event is a DisplayObject on stage and a parent of the object firing the event. You can capture the events in the capture(before) or bubbling(after) phase depending on Listner and Event setup you use. Does this system lend itself well for game programming? When is this system useful? Could you give an example of a case where using events is a lot better than going without them? Are they somehow better for performance in games? Please do not mention events you must use to get a game running, like Event.ENTER_FRAME Or events that are required to get input from the user like, KeyboardEvent.KEY_DOWN and MouseEvent.CLICK. I am asking if there is any use in firing events that have nothing to do with user input, frame rendering and the likes(that are necessary). I am referring to cases where objects are communicating. Is this used to avoid storing a collection of objects that are on the stage? Thanks Here is some code I wrote as an example of event behavior in ActionScript 3, enjoy. package regression { import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.EventPhase; /** * ... * @author ... */ public class Check_event_listening_1 extends Sprite { public const EVENT_DANCE : String = "dance"; public const EVENT_PLAY : String = "play"; public const EVENT_YELL : String = "yell"; private var baby : Shape = new Shape(); private var mom : Sprite = new Sprite(); private var stranger : EventDispatcher = new EventDispatcher(); public function Check_event_listening_1() { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private function init(e:Event = null):void { trace("test begun"); addChild(mom); mom.addChild(baby); stage.addEventListener(EVENT_YELL, onEvent); this.addEventListener(EVENT_YELL, onEvent); mom.addEventListener(EVENT_YELL, onEvent); baby.addEventListener(EVENT_YELL, onEvent); stranger.addEventListener(EVENT_YELL, onEvent); trace("\nTest1 - Stranger yells with no bubbling"); stranger.dispatchEvent(new Event(EVENT_YELL, false)); trace("\nTest2 - Stranger yells with bubbling"); stranger.dispatchEvent(new Event(EVENT_YELL, true)); stage.addEventListener(EVENT_PLAY, onEvent); this.addEventListener(EVENT_PLAY, onEvent); mom.addEventListener(EVENT_PLAY, onEvent); baby.addEventListener(EVENT_PLAY, onEvent); stranger.addEventListener(EVENT_PLAY, onEvent); trace("\nTest3 - baby plays with no bubbling"); baby.dispatchEvent(new Event(EVENT_PLAY, false)); trace("\nTest4 - baby plays with bubbling"); baby.dispatchEvent(new Event(EVENT_PLAY, true)); trace("\nTest5 - baby plays with bubbling but is not a child of mom"); mom.removeChild(baby); baby.dispatchEvent(new Event(EVENT_PLAY, true)); mom.addChild(baby); stage.addEventListener(EVENT_DANCE, onEvent, true); this.addEventListener(EVENT_DANCE, onEvent, true); mom.addEventListener(EVENT_DANCE, onEvent, true); baby.addEventListener(EVENT_DANCE, onEvent); trace("\nTest6 - Mom dances without bubbling - everyone is listening during capture phase(not target and bubble phase)"); mom.dispatchEvent(new Event(EVENT_DANCE, false)); trace("\nTest7 - Mom dances with bubbling - everyone is listening during capture phase(not target and bubble phase)"); mom.dispatchEvent(new Event(EVENT_DANCE, true)); } private function onEvent(e : Event):void { trace("Event was captured"); trace("\nTYPE : ", e.type, "\nTARGET : ", objToName(e.target), "\nCURRENT TARGET : ", objToName(e.currentTarget), "\nPHASE : ", phaseToString(e.eventPhase)); } private function phaseToString(phase : int):String { switch(phase) { case EventPhase.AT_TARGET : return "TARGET"; case EventPhase.BUBBLING_PHASE : return "BUBBLING"; case EventPhase.CAPTURING_PHASE : return "CAPTURE"; default: return "UNKNOWN"; } } private function objToName(obj : Object):String { if (obj == stage) return "STAGE"; else if (obj == this) return "MAIN"; else if (obj == mom) return "Mom"; else if (obj == baby) return "Baby"; else if (obj == stranger) return "Stranger"; else return "Unknown" } } } /*result : test begun Test1 - Stranger yells with no bubbling Event was captured TYPE : yell TARGET : Stranger CURRENT TARGET : Stranger PHASE : TARGET Test2 - Stranger yells with bubbling Event was captured TYPE : yell TARGET : Stranger CURRENT TARGET : Stranger PHASE : TARGET Test3 - baby plays with no bubbling Event was captured TYPE : play TARGET : Baby CURRENT TARGET : Baby PHASE : TARGET Test4 - baby plays with bubbling Event was captured TYPE : play TARGET : Baby CURRENT TARGET : Baby PHASE : TARGET Event was captured TYPE : play TARGET : Baby CURRENT TARGET : Mom PHASE : BUBBLING Event was captured TYPE : play TARGET : Baby CURRENT TARGET : MAIN PHASE : BUBBLING Event was captured TYPE : play TARGET : Baby CURRENT TARGET : STAGE PHASE : BUBBLING Test5 - baby plays with bubbling but is not a child of mom Event was captured TYPE : play TARGET : Baby CURRENT TARGET : Baby PHASE : TARGET Test6 - Mom dances without bubbling - everyone is listening during capture phase(not target and bubble phase) Event was captured TYPE : dance TARGET : Mom CURRENT TARGET : STAGE PHASE : CAPTURE Event was captured TYPE : dance TARGET : Mom CURRENT TARGET : MAIN PHASE : CAPTURE Test7 - Mom dances with bubbling - everyone is listening during capture phase(not target and bubble phase) Event was captured TYPE : dance TARGET : Mom CURRENT TARGET : STAGE PHASE : CAPTURE Event was captured TYPE : dance TARGET : Mom CURRENT TARGET : MAIN PHASE : CAPTURE */

    Read the article

  • Searching over a templated tree

    - by floatingfrisbee
    So I have 2 interfaces: A node that can have children public interface INode { IEnumeration<INode> Children { get; } void AddChild(INode node); } And a derived "Data Node" that can have data associated with it public interface IDataNode<DataType> : INode { DataType Data; IDataNode<DataType> FindNode(DataType dt); } Keep in mind that each node in the tree could have a different data type associated with it as its Data (because the INode.AddChild function just takes the base INode) Here is the implementation of the IDataNode interface: internal class DataNode<DataType> : IDataNode<DataType> { List<INode> m_Children; DataNode(DataType dt) { Data = dt; } public IEnumerable<INode> Children { get { return m_Children; } } public void AddChild(INode node) { if (null == m_Children) m_Children = new List<INode>(); m_Children.Add(node); } public DataType Data { get; private set; } Question is how do I implement the FindNode function without knowing what kinds of DataType I will encounter in the tree? public IDataNode<DataType> FindNode(DataType dt) { throw new NotImplementedException(); } } As you can imagine something like this will not work out public IDataNode<DataType> FindNode(DataType dt) { IDataNode<DataType> result = null; foreach (var child in Children) { if (child is IDataNode<DataType>) { var datachild = child as IDataNode<DataType>; if (datachild.Data.Equals(dt)) { result = child as IDataNode<DataType>; break; } } else { // What?? } } return result; } Is my only option to do this when I know what kinds of DataType a particular tree I use will have? Maybe I am going about this in the wrong way, so any tips are appreciated. Thanks!

    Read the article

  • array data taking XML value is not taking css value in as3

    - by Sagar S. Ranpise
    I have xml structure all data comes here inside CDATA I am using css file in it to format text and classes are mentioned in xml Below is the code which shows data but does not format with CSS. Thanks in advance! var myXML:XML = new XML(); var myURLLoader:URLLoader = new URLLoader(); var myURLRequest:URLRequest = new URLRequest("test.xml"); myURLLoader.load(myURLRequest); //////////////For CSS/////////////// var myCSS:StyleSheet = new StyleSheet(); var myCSSURLLoader:URLLoader = new URLLoader(); var myCSSURLRequest:URLRequest = new URLRequest("test.css"); myCSSURLLoader.load(myCSSURLRequest); myCSSURLLoader.addEventListener(Event.COMPLETE,processXML); var i:int; var textHeight:int = 0; var textPadding:int = 10; var txtName:TextField = new TextField(); var myMov:MovieClip = new MovieClip(); var myMovGroup:MovieClip = new MovieClip(); var myArray:Array = new Array(); function processXML(e:Event):void { myXML = new XML(myURLLoader.data); trace(myXML.person.length()); var total:int = myXML.person.length(); trace("total" + total); for(i=0; i<total; i++) { myArray.push({name: myXML.person[i].name.toString()}); trace(myArray[i].name); } processCSS(); } function processCSS():void { myCSS.parseCSS(myCSSURLLoader.data); for(i=0; i<myXML.person.length(); i++) { myMov.addChild(textConvertion(myArray[i].name)); myMov.y = textHeight; textHeight += myMov.height + textPadding; trace("Text: "+myXML.person[i].name); myMovGroup.addChild(myMov); } this.addChild(myMovGroup); } function textConvertion(textConverted:String) { var tc:TextField = new TextField(); tc.htmlText = textConverted; tc.multiline = true; tc.wordWrap = true; tc.autoSize = TextFieldAutoSize.LEFT; tc.selectable = true; tc.y = textHeight; textHeight += tc.height + textPadding; tc.styleSheet = myCSS; return tc; }

    Read the article

  • programmatically add views to a viewstack flex

    - by dubbeat
    Hi, I'm trying to figure out how to in as3 (not mxml) add views to a view stack. For example I have a view component like so package components.screens { import mx.controls.Label; import mx.core.UIComponent; public class HomeScreen extends UIComponent { private var l:Label=new Label() public function HomeScreen() { super(); l.text="home"; addChild(l) } } } I've being trying to add it to a viewstack in the following way var myStack:ViewStack= new ViewStack(); mystack.addChild(homeScreen) This does not work. Whats the correct way? I'm aware I have to assign ID's but for now I just want to get the view in there

    Read the article

  • Java3d shape with Antlr

    - by Eldeus
    Well how to evaluate a very simple antlr grammar that does only this. Box(1,2,4) Cylinder(1,2) and builds java3d shapes, (given I have already built a canvas for java3d and have the code for creating each element in java, protected static BranchGroup addBox1(Float a, Float b, Float C){ // create branch for display TransformGroup bodyTransform = new TransformGroup(); BranchGroup bg = new BranchGroup(); bg.setCapability(BranchGroup.ALLOW_DETACH); bg.setUserData(shapeId); // set transformation bodyTransform = setTransformShape(0,0,0,0,0,0,0); // create box Box tmpBox = new Box(a,b,c, Primitive.GENERATE_NORMALS | Primitive.GENERATE_TEXTURE_COORDS,setAppearance(color)); getCoords(tmpBox); bodyTransform.addChild(tmpBox); trFormList.add(bodyTransform); shapeId++; //add box to branch bg.addChild(bodyTransform); return bg; } ) thanks

    Read the article

  • How to Make a Game like Space Invaders - Ray Wenderlich (why do my space invaders scroll off screen)

    - by Erv Noel
    I'm following this tutorial(http://www.raywenderlich.com/51068/how-to-make-a-game-like-space-invaders-with-sprite-kit-tutorial-part-1) and I've run into a problem right after the part where I add [self determineInvaderMovementDirection]; to my GameScene.m file (specifically to my moveInvadersForUpdate method) The tutorial states that the space invaders should be moving accordingly after adding this piece of code but when I run they move to the left and they do not come back. I'm not sure what I am doing wrong as I have followed this tutorial very carefully. Any help or clarification would be greatly appreciated. Thanks in advance ! Here is the full GameScene.m #import "GameScene.h" #import <CoreMotion/CoreMotion.h> #pragma mark - Custom Type Definitions /* The type definition and constant definitions 1,2,3 take care of the following tasks: 1.Define the possible types of invader enemies. This can be used in switch statements later when things like displaying different sprites images for each enemy type. The typedef makes InvaderType a formal Obj-C type that is type checked for method arguments and variables.This is so that the wrong method argument is not used or assigned to the wrong variable. 2. Define the size of the invaders and that they'll be laid out in a grid of rows and columns on the screen. 3. Define a name that will be used to identify invaders when searching for them. */ //1 typedef enum InvaderType { InvaderTypeA, InvaderTypeB, InvaderTypeC } InvaderType; /* Invaders move in a fixed pattern: right, right, down, left, down, right right. InvaderMovementDirection tracks the invaders' progress through this pattern */ typedef enum InvaderMovementDirection { InvaderMovementDirectionRight, InvaderMovementDirectionLeft, InvaderMovementDirectionDownThenRight, InvaderMovementDirectionDownThenLeft, InvaderMovementDirectionNone } InvaderMovementDirection; //2 #define kInvaderSize CGSizeMake(24,16) #define kInvaderGridSpacing CGSizeMake(12,12) #define kInvaderRowCount 6 #define kInvaderColCount 6 //3 #define kInvaderName @"invader" #define kShipSize CGSizeMake(30, 16) //stores the size of the ship #define kShipName @"ship" // stores the name of the ship stored on the sprite node #define kScoreHudName @"scoreHud" #define kHealthHudName @"healthHud" /* this class extension allows you to add “private” properties to GameScene class, without revealing the properties to other classes or code. You still get the benefit of using Objective-C properties, but your GameScene state is stored internally and can’t be modified by other external classes. As well, it doesn’t clutter the namespace of datatypes that your other classes see. This class extension is used in the method didMoveToView */ #pragma mark - Private GameScene Properties @interface GameScene () @property BOOL contentCreated; @property InvaderMovementDirection invaderMovementDirection; @property NSTimeInterval timeOfLastMove; @property NSTimeInterval timePerMove; @end @implementation GameScene #pragma mark Object Lifecycle Management #pragma mark - Scene Setup and Content Creation /*This method simply invokes createContent using the BOOL property contentCreated to make sure you don’t create your scene’s content more than once. This property is defined in an Objective-C Class Extension found near the top of the file()*/ - (void)didMoveToView:(SKView *)view { if (!self.contentCreated) { [self createContent]; self.contentCreated = YES; } } - (void)createContent { //1 - Invaders begin by moving to the right self.invaderMovementDirection = InvaderMovementDirectionRight; //2 - Invaders take 1 sec for each move. Each step left, right or down // takes 1 second. self.timePerMove = 1.0; //3 - Invaders haven't moved yet, so set the time to zero self.timeOfLastMove = 0.0; [self setupInvaders]; [self setupShip]; [self setupHud]; } /* Creates an invade sprite of a given type 1. Use the invadeType parameterr to determine color of the invader 2. Call spriteNodeWithColor:size: of SKSpriteNode to alloc and init a sprite that renders as a rect of the given color invaderColor with size kInvaderSize */ -(SKNode*)makeInvaderOfType:(InvaderType)invaderType { //1 SKColor* invaderColor; switch (invaderType) { case InvaderTypeA: invaderColor = [SKColor redColor]; break; case InvaderTypeB: invaderColor = [SKColor greenColor]; break; case InvaderTypeC: invaderColor = [SKColor blueColor]; break; } //2 SKSpriteNode* invader = [SKSpriteNode spriteNodeWithColor:invaderColor size:kInvaderSize]; invader.name = kInvaderName; return invader; } -(void)setupInvaders { //1 - loop over the rows CGPoint baseOrigin = CGPointMake(kInvaderSize.width / 2, 180); for (NSUInteger row = 0; row < kInvaderRowCount; ++row) { //2 - Choose a single InvaderType for all invaders // in this row based on the row number InvaderType invaderType; if (row % 3 == 0) invaderType = InvaderTypeA; else if (row % 3 == 1) invaderType = InvaderTypeB; else invaderType = InvaderTypeC; //3 - Does some math to figure out where the first invader // in the row should be positioned CGPoint invaderPosition = CGPointMake(baseOrigin.x, row * (kInvaderGridSpacing.height + kInvaderSize.height) + baseOrigin.y); //4 - Loop over the columns for (NSUInteger col = 0; col < kInvaderColCount; ++col) { //5 - Create an invader for the current row and column and add it // to the scene SKNode* invader = [self makeInvaderOfType:invaderType]; invader.position = invaderPosition; [self addChild:invader]; //6 - update the invaderPosition so that it's correct for the //next invader invaderPosition.x += kInvaderSize.width + kInvaderGridSpacing.width; } } } -(void)setupShip { //1 - creates ship using makeShip. makeShip can easily be used later // to create another ship (ex. to set up more lives) SKNode* ship = [self makeShip]; //2 - Places the ship on the screen. In SpriteKit the origin is at the lower //left corner of the screen. The anchorPoint is based on a unit square with (0, 0) at the lower left of the sprite's area and (1, 1) at its top right. Since SKSpriteNode has a default anchorPoint of (0.5, 0.5), i.e., its center, the ship's position is the position of its center. Positioning the ship at kShipSize.height/2.0f means that half of the ship's height will protrude below its position and half above. If you check the math, you'll see that the ship's bottom aligns exactly with the bottom of the scene. ship.position = CGPointMake(self.size.width / 2.0f, kShipSize.height/2.0f); [self addChild:ship]; } -(SKNode*)makeShip { SKNode* ship = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor] size:kShipSize]; ship.name = kShipName; return ship; } -(void)setupHud { //Sets the score label font to Courier SKLabelNode* scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"Courier"]; //1 - Give the score label a name so it becomes easy to find later when // the score needs to be updated. scoreLabel.name = kScoreHudName; scoreLabel.fontSize = 15; //2 - Color the score label green scoreLabel.fontColor = [SKColor greenColor]; scoreLabel.text = [NSString stringWithFormat:@"Score: %04u", 0]; //3 - Positions the score label near the top left corner of the screen scoreLabel.position = CGPointMake(20 + scoreLabel.frame.size.width/2, self.size.height - (20 + scoreLabel.frame.size.height/2)); [self addChild:scoreLabel]; //Applies the font of the health label SKLabelNode* healthLabel = [SKLabelNode labelNodeWithFontNamed:@"Courier"]; //4 - Give the health label a name so it can be referenced later when it needs // to be updated to display the health healthLabel.name = kHealthHudName; healthLabel.fontSize = 15; //5 - Colors the health label red healthLabel.fontColor = [SKColor redColor]; healthLabel.text = [NSString stringWithFormat:@"Health: %.1f%%", 100.0f]; //6 - Positions the health Label on the upper right hand side of the screen healthLabel.position = CGPointMake(self.size.width - healthLabel.frame.size.width/2 - 20, self.size.height - (20 + healthLabel.frame.size.height/2)); [self addChild:healthLabel]; } #pragma mark - Scene Update - (void)update:(NSTimeInterval)currentTime { //Makes the invaders move [self moveInvadersForUpdate:currentTime]; } #pragma mark - Scene Update Helpers //This method will get invoked by update -(void)moveInvadersForUpdate:(NSTimeInterval)currentTime { //1 - if it's not yet time to move, exit the method. moveInvadersForUpdate: // is invoked 60 times per second, but you don't want the invaders to move // that often since the movement would be too fast to see if (currentTime - self.timeOfLastMove < self.timePerMove) return; //2 - Recall that the scene holds all the invaders as child nodes; which were // added to the scene using addChild: in setupInvaders identifying each invader // by its name property. Invoking enumerateChildNodesWithName:usingBlock only loops over the invaders because they're named kInvaderType; which makes the loop skip the ship and the HUD. The guts og the block moves the invaders 10 pixels either right, left or down depending on the value of invaderMovementDirection [self enumerateChildNodesWithName:kInvaderName usingBlock:^(SKNode *node, BOOL *stop) { switch (self.invaderMovementDirection) { case InvaderMovementDirectionRight: node.position = CGPointMake(node.position.x - 10, node.position.y); break; case InvaderMovementDirectionLeft: node.position = CGPointMake(node.position.x - 10, node.position.y); break; case InvaderMovementDirectionDownThenLeft: case InvaderMovementDirectionDownThenRight: node.position = CGPointMake(node.position.x, node.position.y - 10); break; InvaderMovementDirectionNone: default: break; } }]; //3 - Record that you just moved the invaders, so that the next time this method is invoked (1/60th of a second from when it starts), the invaders won't move again until the set time period of one second has elapsed. self.timeOfLastMove = currentTime; //Makes it so that the invader movement direction changes only when the invaders are actually moving. Invaders only move when the check on self.timeOfLastMove passes (when conditional expression is true) [self determineInvaderMovementDirection]; } #pragma mark - Invader Movement Helpers -(void)determineInvaderMovementDirection { //1 - Since local vars accessed by block are default const(means they cannot be changed), this snippet of code qualifies proposedMovementDirection with __block so that you can modify it in //2 __block InvaderMovementDirection proposedMovementDirection = self.invaderMovementDirection; //2 - Loops over the invaders in the scene and refers to the block with the invader as an argument [self enumerateChildNodesWithName:kInvaderName usingBlock:^(SKNode *node, BOOL *stop) { switch (self.invaderMovementDirection) { case InvaderMovementDirectionRight: //3 - If the invader's right edge is within 1pt of the right edge of the scene, it's about to move offscreen. Sets proposedMovementDirection so that the invaders move down then left. You compare the invader's frame(the frame that contains its content in the scene's coordinate system) with the scene width. Since the scene has an anchorPoint of (0,0) by default and is scaled to fill it's parent view, this comparison ensures you're testing against the view's edges. if (CGRectGetMaxX(node.frame) >= node.scene.size.width - 1.0f) { proposedMovementDirection = InvaderMovementDirectionDownThenLeft; *stop = YES; } break; case InvaderMovementDirectionLeft: //4 - If the invader's left edge is within 1 pt of the left edge of the scene, it's about to move offscreen. Sets the proposedMovementDirection so invaders move down then right if (CGRectGetMinX(node.frame) <= 1.0f) { proposedMovementDirection = InvaderMovementDirectionDownThenRight; *stop = YES; } break; case InvaderMovementDirectionDownThenLeft: //5 - If invaders are moving down then left, they already moved down at this point, so they should now move left. proposedMovementDirection = InvaderMovementDirectionLeft; *stop = YES; break; case InvaderMovementDirectionDownThenRight: //6 - if the invaders are moving down then right, they already moved down so they should now move right. proposedMovementDirection = InvaderMovementDirectionRight; *stop = YES; break; default: break; } }]; //7 - if the proposed invader movement direction is different than the current invader movement direction, update the current direction to the proposed direction if (proposedMovementDirection != self.invaderMovementDirection) { self.invaderMovementDirection = proposedMovementDirection; } } #pragma mark - Bullet Helpers #pragma mark - User Tap Helpers #pragma mark - HUD Helpers #pragma mark - Physics Contact Helpers #pragma mark - Game End Helpers @end

    Read the article

  • Actionscript Receiving Mouse Events For Lower Indexed And Partially Covered Display Objects?

    - by Chunk1978
    i have 2 sprites on stage. bottomSprite is added to the display list first, followed by topSprite. topSprite partially covers bottomSprite. i've added an event listener to bottomSprite for MouseEvent.MOUSE_MOVED notifications to simply trace the mouseX and mouseY coordinates. however, the notification doesn't work for the parts of bottomSprite that are covered by topSprite. var bottomSprite:Sprite = new Sprite(); bottomSprite.graphics.beginFill(0x666666, 0.5); bottomSprite.graphics.drawRect(150,150, 150, 150); bottomSprite.graphics.endFill(); addChild(bottomSprite); var topSprite:Sprite = new Sprite(); topSprite.graphics.beginFill(0x00FFFF, 0.5); topSprite.graphics.drawRect(250,50, 150, 150); topSprite.graphics.endFill(); addChild(topSprite); bottomSprite.addEventListener(MouseEvent.MOUSE_MOVE, traceCoords); function traceCoords(evt:MouseEvent):void { trace ("Coord = X:" + bottomSprite.mouseX + ", Y:" + bottomSprite.mouseY); }

    Read the article

  • UIComponent's width and height have no effect on Sprite

    - by flexwheel
    Given this code: var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xFFCC00); circle.graphics.drawCircle(0, 0, 20); var uiComp:UIComponent = new UIComponent(); uiComp.x = 100; uiComp.y = 100; uiComp.measuredHeight = 0; uiComp.measuredWidth = 0; uiComp.addChild(circle); addChild(uiComp); Why does changing the width and height of uiComp not affect the Sprite? Wouldn't UIComponent provide Sprite with a Graphics object, which limits that area where Sprite can draw?

    Read the article

  • -[CCScene setOffsetx:]: unrecognized selector sent to instance

    - by Alexander Sharunov
    please help me, i'm very new in objective-c i've got 2 simplest classes (bellow first, second) i would like to set the offsetx properties of self.rolypoly object in second class like a self.rolypoly.offsetx=1 or run use [self.rolypoly setOffx]; to do somethings, but i always have the errors: trying [self.rolypoly setOffx]; in second class -[CCScene setOffx:]: unrecognized selector sent to instance 0x91d0b70' or trying self.rolypoly.offsetx=1; in second class -[CCScene setOffsetx:]: unrecognized selector sent to instance 0x808bfc0' first class //************************************************************ #import <Foundation/Foundation.h> #import "cocos2d.h" @interface RolyPoly : CCLayer { CCAction *_walkAction; CCSprite *_rolypoly; int offsetx; int offsety; } @property (nonatomic, retain) CCSprite *rolypoly; @property (nonatomic, retain) CCAction *walkAction; @property (nonatomic, assign) int offsetx; @property (nonatomic, assign) int offsety; +(id) scene; -(void) setOffx; @end //************************************************************ #import "GameLayer.h" #import "RolyPoly.h" @implementation RolyPoly @synthesize rolypoly = _rolypoly; @synthesize walkAction = _walkAction; @synthesize offsetx = _offsetx; @synthesize offsety = _offsety; +(id) scene { CCScene *scene = [CCScene node]; RolyPoly *layer = [RolyPoly node]; [scene addChild: layer]; return scene; } -(id) init { if ((self = [super init])) { [self scheduleUpdate]; } return self; } -(void) setOffx { NSLog(@"setOffx"); } -(void) update:(ccTime)delta { } - (void) dealloc { self.rolypoly = nil; self.walkAction = nil; [super dealloc]; } @end second class //************************************************************ #import <Foundation/Foundation.h> #import "cocos2d.h" #import "RolyPoly.h" @interface GameLayer : CCLayer { RolyPoly *_rolypoly; } // returns a CCScene that contains the HelloWorldLayer as the only child +(CCScene *) scene; @property (nonatomic, assign) RolyPoly * rolypoly; @end //************************************************************ #import "GameLayer.h" #import "RolyPoly.h" // HelloWorldLayer implementation @implementation GameLayer @synthesize rolypoly = _rolypoly; +(CCScene *) scene { CCScene *scene = [CCScene node]; GameLayer *layer = [GameLayer node]; [scene addChild: layer]; return scene; } -(id) init { if( (self=[super init])) { CGSize screenSize = [[CCDirector sharedDirector] winSize]; self.rolypoly = [RolyPoly scene]; [self addChild:self.rolypoly z:1]; [self.rolypoly setOffx]; [self scheduleUpdate]; } return self; } - (void)update:(ccTime)dt { } - (void) dealloc { [super dealloc]; } @end

    Read the article

  • mx.core::BitmapAsset could not be found

    - by asksuperuser
    I tried the code EmbedAssets.as below found in sample here: http://www.senocular.com/flash/tutorials/as3withmxmlc/ I got this error when building with mxmlc.exe and testing the ouput EmbedAssets.swf in Flash Player 9: VerifyError: Error #1014: mx.core::BitmapAsset could not be found package { import flash.display.Sprite; public class EmbedAssets extends Sprite { [Embed(source="images/trophy.png")] private var TrophyImage:Class; [Embed(source="swfs/satdish.swf")] private var SatelliteAnimation:Class; public function EmbedAssets() { addChild(new SatelliteAnimation()); addChild(new TrophyImage()); } } } satdish.swf is not corrupted so I don't understand why this error message.

    Read the article

  • Error #1009 Cannot access a property or method of a null object reference.

    - by user288920
    Hey everyone, I'm trying to import an external SWF with a scrollbar, calling out to an external .AS, into my main SWF. Someone told me, it's an issue that my scrollbar isn't instantiated yet, but stopped short of helping me how to fix the problem. Here's the error below: TypeError: Error #1009: Cannot access a property or method of a null object reference. at Scrollbar/init() at Sample2_fla::MainTimeline/scInit() at flash.display::DisplayObjectContainer/addChild() at Sample2_fla::MainTimeline/frame1() On my main SWF, I was to click a button and load my external SWF. I want to then click another button in the external SWF and reveal my scrollbar (alpha=1;). The scrollbar is the issue. Here's my script: Sample1.swf (main) this.addEventListener(MouseEvent.CLICK, clickListener); var oldSection=null; function clickListener(evt:Event) { if (evt.target.name=="button_btn") { loadSection("Sample2.swf"); } } function loadSection(filePath:String) { var url:URLRequest=new URLRequest(filePath); var ldr:Loader = new Loader(); ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, sectionLoadedListener); ldr.load(url); } function sectionLoadedListener(evt:Event) { var section=evt.target.content; if (oldSection) { removeChild(oldSection); } oldSection=section; addChild(section); section.x=0; section.y=0; } Sample2.SWF (external): import com.greensock.*; import com.greensock.easing.*; import com.greensock.plugins.*; scroll_mc.alpha=0; import Scrollbar; var sc:Scrollbar=new Scrollbar(scroll_mc.text,scroll_mc.maskmc,scroll_mc.scrollbar.ruler,scroll_mc.scrollbar.background,scroll_mc.area,true,6); sc.addEventListener(Event.ADDED, scInit); addChild(sc); function scInit(e:Event):void { sc.init(); } button2_btn.addEventListener(MouseEvent.CLICK, clickListener); function clickListener(evt:MouseEvent){ TweenMax.to(this.scroll_mc, 1,{alpha:1}); } I really appreciate your help. Cheers!

    Read the article

  • Writing the code by dividing it into more files in cocoatouch.

    - by srikanth rongali
    My problem is, I need a background image, a sprite(with animation) on left edge, another sprite(with animation) at other edge, a number count animation 1-2-3 at middle. I got all these when I wrote all in same file.(like [self addChild:label], [self addChild:sprite].., But in this it needs touch enables for both sprites separately, and touchDisabled to the remaining screen. So thought of writing in different files. But now it is not working. I kept one sprite, background image, numbercount in one file and another spritr in other file. Either I am getting the second sprite or the (sprite+background+numberCount) is displayed. This is my problem. plz give me solution. Thank You

    Read the article

  • Adding mouse events to dynamically loaded SWF

    - by Josamoto
    I am loading an external SWF using the Loader class, and adding it to the stage with addChild. When trying to add a mouse click event listener to the MovieClip, using addEventListener, nothing happens, the event never fires. Is there a specific way to add listeners to externally loaded movie clips? My code looks somewhat like this: var target:MovieClip = assets["screensaver"] as MovieClip; target.root.addEventListener(MouseEvent.CLICK, onClickScreenSaver, true); addChild(target); The target shows up on the display, but the CLICK event is completely ignored.

    Read the article

  • Writing the code iby dividing it into more files.

    - by srikanth rongali
    My problem is, I need a background image, a sprite(with animation) on left edge, another sprite(with animation) at other edge, a number count animation 1-2-3 at middle. I got all these when I wrote all in same file.(like [self addChild:label], [self addChild:sprite].., But in this it needs touch enables for both sprites separately, and touchDisabled to the remaining screen. So thought of writing in different files. But now it is not working. I kept one sprite, background image, numbercount in one file and another spritr in other file. Either I am getting the second sprite or the (sprite+background+numberCount) is displayed. This is my problem. plz give me solution. Thank You

    Read the article

  • AS3 Pass parameter by value

    - by alejandrobog
    Hi, im having problems with the following code: for (var i:Number=0; i<numFaces;i++){ var faceLoader:Loader = new Loader(); faceLoader.contentLoaderInfo.addEventListener( Event.INIT, function(fle:Event){ LoadCara(i,faceLoader); trace("LoadCara:" + i.toString()); } ); } function LoadCara(index:int,loader:Loader){ if(index == 0) { trace("cara1:" + index.toString()); cara1.removeChildAt(0); cara1.addChild(loader); } else if(index == 1) { cara2.removeChildAt(0); cara2.addChild(loader); }} The problem is that im sending the variable i to the function LoadCara on every iteration, and its always called with the last value of i. I would like this function to be called with the appropiate index. Hope I explain myself, thanks in advance.

    Read the article

  • Why doesn't variable img increase?

    - by Annette B
    I can upload image but the sprite name remains pict1 each time I upload another image. Why doesn't imgVal function increase? function imgVal() { img += 1; trace("image: pict" + img); } imgVal(); _fla.lights_mc.visible=false; _fla.lights_mc.stop(); _fla.pre_mc.fill_mc.stop(); _fla.pre_mc.visible=false; var sprite:Sprite=new Sprite(); sprite.addChild(loader); sprite.name = "pict" + img; //trace(sprite.name); _fla.myBorder.box.addChild(sprite); I'd like each sprite to be given a new name like pict1, pict2, pict3, etc but img variable is not increasing. I think this is where my problem occurs. Would someone please help?

    Read the article

  • Cocos2d-x Spritebatch node animation appears to be broken? cocos2d-x 2.0.3

    - by George Host
    Hi I have spent aprox 2 days trying to get this to work doing a google searches left and right and I did get it working except for sprite batch nodes. So in my class I am able to load kuwalio_stand.png and I tested kuwalio_walk1.png and 2 and 3 from the FrameCache(). They work for sure 100%. I run this code and it does not animate does anyone else have the same issue with sprite batch nodes? cocos2d::CCSprite * player = Player::create(); player->setPosition(cocos2d::CCPointMake(0.0f,0.0f)); player->setDisplayFrame(cocos2d::CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("kuwalio_stand.png")); player->setTag(PlayerTag); cocos2d::CCAnimation * walk = cocos2d::CCAnimation::create(); cocos2d::CCSpriteFrame * walk1 = cocos2d::CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("kuwalio_walk1"); cocos2d::CCSpriteFrame * walk2 = cocos2d::CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("kuwalio_walk2"); cocos2d::CCSpriteFrame * walk3 = cocos2d::CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("kuwalio_walk3"); walk->addSpriteFrame(walk1); walk->addSpriteFrame(walk2); walk->addSpriteFrame(walk3); cocos2d::CCAnimate * actionWalk = cocos2d::CCAnimate::create(walk); cocos2d::CCRepeatForever * actionRepeat = cocos2d::CCRepeatForever::create(actionWalk); walk->setDelayPerUnit(0.1f); actionWalk->setDuration(10.1f); this->runAction(actionRepeat); // Change camera to a soft follow camera. this->runAction(cocos2d::CCFollow::create(player)); mSceneSpriteBatchNode->addChild(player); // Have the CCNode object run its virtual update function as fast as possible. // Every frame for this layer. this-scheduleUpdate(); Counter example without the sprite batch node... cocos2d::CCSprite * sprite = cocos2d::CCSprite::create("kuwalio_walk1.png"); this->addChild(sprite,0); sprite->setPosition(cocos2d::CCPointMake(60,60)); sprite->retain(); cocos2d::CCAnimation * actionAnimation = cocos2d::CCAnimation::create(); actionAnimation->setDelayPerUnit(0.01f); actionAnimation->retain(); actionAnimation->addSpriteFrameWithFileName("kuwalio_walk1.png"); actionAnimation->addSpriteFrameWithFileName("kuwalio_walk2.png"); actionAnimation->addSpriteFrameWithFileName("kuwalio_walk3.png"); cocos2d::CCAnimate * a = cocos2d::CCAnimate::create(actionAnimation); a->setDuration(0.10f); cocos2d::CCRepeatForever * actionRepeat = cocos2d::CCRepeatForever::create(a); sprite->runAction(actionRepeat);

    Read the article

  • Cocos3d lighting problem

    - by Parasithe
    I'm currently working on a cocos3d project, but I'm having some trouble with lighting and I have no idea how to solve it. I've tried everything and the lighting is always as bad in the game. The first picture is from 3ds max (the software we used for 3d) and the second is from my iphone app. http://prntscr.com/ly378 http://prntscr.com/ly2io As you can see, the lighting is really bad in the app. I manually add my spots and the ambiant light. Here is all my lighting code : _spot = [CC3Light lightWithName: @"Spot" withLightIndex: 0]; // Set the ambient scene lighting. ccColor4F ambientColor = { 0.9, 0.9, 0.9, 1 }; self.ambientLight = ambientColor; //Positioning _spot.target = [self getNodeNamed:kCharacterName]; _spot.location = cc3v( 400, 400, -600 ); // Adjust the relative ambient and diffuse lighting of the main light to // improve realisim, particularly on shadow effects. _spot.diffuseColor = CCC4FMake(0.8, 0.8, 0.8, 1.0); _spot.specularColor = CCC4FMake(0, 0, 0, 1); [_spot setAttenuationCoefficients:CC3AttenuationCoefficientsMake(0, 0, 1)]; // Another mechansim for adjusting shadow intensities is shadowIntensityFactor. // For better effect, set here to a value less than one to lighten the shadows // cast by the main light. _spot.shadowIntensityFactor = 0.75; [self addChild:_spot]; _spot2 = [CC3Light lightWithName: @"Spot2" withLightIndex: 1]; //Positioning _spot2.target = [self getNodeNamed:kCharacterName]; _spot2.location = cc3v( -550, 400, -800 ); _spot2.diffuseColor = CCC4FMake(0.8, 0.8, 0.8, 1.0); _spot2.specularColor = CCC4FMake(0, 0, 0, 1); [_spot2 setAttenuationCoefficients:CC3AttenuationCoefficientsMake(0, 0, 1)]; _spot2.shadowIntensityFactor = 0.75; [self addChild:_spot2]; I'd really appreciate if anyone would have some tip on how to fix the lighting. Maybe my spots are bad? maybe it's the material? I really have no idea. Any help would be welcomed. I already ask some help on cocos2d forums. I had some answers but I need more help.

    Read the article

  • Spritebatch node animation appears to be broken in cocos2d-x 2.0.3

    - by George Host
    Hi I have spent aprox 2 days trying to get this to work doing a google searches left and right and I did get it working except for sprite batch nodes. So in my class I am able to load kuwalio_stand.png and I tested kuwalio_walk1.png and 2 and 3 from the FrameCache(). They work for sure 100%. I run this code and it does not animate does anyone else have the same issue with sprite batch nodes? cocos2d::CCSprite * player = Player::create(); player->setPosition(cocos2d::CCPointMake(0.0f,0.0f)); player->setDisplayFrame(cocos2d::CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("kuwalio_stand.png")); player->setTag(PlayerTag); cocos2d::CCAnimation * walk = cocos2d::CCAnimation::create(); cocos2d::CCSpriteFrame * walk1 = cocos2d::CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("kuwalio_walk1.png"); cocos2d::CCSpriteFrame * walk2 = cocos2d::CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("kuwalio_walk2.png"); cocos2d::CCSpriteFrame * walk3 = cocos2d::CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("kuwalio_walk3.png"); walk->addSpriteFrame(walk1); walk->addSpriteFrame(walk2); walk->addSpriteFrame(walk3); cocos2d::CCAnimate * actionWalk = cocos2d::CCAnimate::create(walk); cocos2d::CCRepeatForever * actionRepeat = cocos2d::CCRepeatForever::create(actionWalk); walk->setDelayPerUnit(0.1f); actionWalk->setDuration(10.1f); player->runAction(actionRepeat); // Change camera to a soft follow camera. this->runAction(cocos2d::CCFollow::create(player)); mSceneSpriteBatchNode->addChild(player); // Have the CCNode object run its virtual update function as fast as possible. // Every frame for this layer. this-scheduleUpdate(); Counter example without the sprite batch node... cocos2d::CCSprite * sprite = cocos2d::CCSprite::create("kuwalio_walk1.png"); this->addChild(sprite,0); sprite->setPosition(cocos2d::CCPointMake(60,60)); sprite->retain(); cocos2d::CCAnimation * actionAnimation = cocos2d::CCAnimation::create(); actionAnimation->setDelayPerUnit(0.01f); actionAnimation->retain(); actionAnimation->addSpriteFrameWithFileName("kuwalio_walk1.png"); actionAnimation->addSpriteFrameWithFileName("kuwalio_walk2.png"); actionAnimation->addSpriteFrameWithFileName("kuwalio_walk3.png"); cocos2d::CCAnimate * a = cocos2d::CCAnimate::create(actionAnimation); a->setDuration(0.10f); cocos2d::CCRepeatForever * actionRepeat = cocos2d::CCRepeatForever::create(a); sprite->runAction(actionRepeat);

    Read the article

  • How can I place a ProgressBar in Android using Cocos 2d?

    - by Laxmipriya
    I want to place a horizontal progress bar in my Android application and I want to change its progress color. I used the following code, but the progress bar is not being displayed. CCProgressTimer progressBar = CCProgressTimer.progress("progressbar.png"); progressBar.setType(kCCProgressTimerTypeHorizontalBarLR); progressBar.setScale(5); progressBar.setAnchorPoint(CGPoint.ccp(0, 0)); progressBar.setPosition(CGPoint.ccp(0,0)); addChild(progressBar);

    Read the article

  • Away3D & Directional Light w/ Rotating Meshes

    - by seethru
    This is likely a stupid error but I can't seem to find what I've done wrong. I've got a simple scene with 10 cylinders rotating at a default speed. If I grab one of these cylinders I can rotate it in the opposite direction or at a greater speed. I have a single directional light in the scene. It would appear that the directional light is only calculated at initialization and not on further frames. The shadow created by the light rotates with the cylinder giving the impression that the light is rotating when it isn't. Camera & Light Initialization _view = new View3D(); addChild(_view); _view.antiAlias = 4; _view.backgroundColor = 0xFFFFFF; _view.camera.z = -850; _view.camera.y = 0; _view.camera.x = 0; _view.camera.lookAt(new Vector3D()); _view.camera.lens = new PerspectiveLens(15); _view.mousePicker = PickingType.RAYCAST_BEST_HIT; _light = new DirectionalLight(); _light.z = -850; _light.direction = new Vector3D(1, 1, 1); _light.color = 0xFFFFFF; _light.ambient = 0.1; _light.diffuse = 0.7; _view.scene.addChild(_light); Mesh and Material creation var material:TextureMaterial = new TextureMaterial(createPow2Texture(sprite, _colors[i]) , true, false, true); material.animateUVs = true; material.lightPicker = _lightPicker; cylinder = new Mesh(new CylinderGeometry(radius, radius, 13, 70, 1, true, true), material); cylinder.subMeshes[0].scaleU = spriteWidth / sprite.width; cylinder.y = y; cylinder.mouseEnabled = true; cylinder.pickingCollider = PickingColliderType.AS3_BEST_HIT; cylinder.addEventListener(MouseEvent3D.MOUSE_OVER, onMouseOverMesh); cylinder.addEventListener(MouseEvent3D.MOUSE_MOVE, onMouseOverMesh); cylinder.addEventListener(MouseEvent3D.MOUSE_OUT, onMouseOutMesh); _cylinders.push(cylinder); Frame private function onEnterFrame(event:Event):void { for each (var mesh:Mesh in _cylinders) { if (mesh == _mouseOverMesh) continue; mesh.rotationY += 0.25; } _view.render(); }

    Read the article

  • problem in array of shooter sprites which contain different colour bubbles

    - by prakash s
    everyone i am developing bubble shooter game in cocos2d I have placed shooter array which contain different color bubbles like this 00000000 it is 8 bubbles array if i tap the screen, first bubbles should move for shooting the target .png .And if i again tap the screen again 2nd position bubble should move for shooting the target.png bubbles,how it will possible for me because i have already created the array of target which contain different color bubbles, here i write the code : - (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // Choose one of the touches to work with UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInView:[touch view]]; location = [[CCDirector sharedDirector] convertToGL:location]; // Set up initial location of projectile CGSize winSize = [[CCDirector sharedDirector] winSize]; NSMutableArray * movableSprites = [[NSMutableArray alloc] init]; NSArray *images = [NSArray arrayWithObjects:@"1.png", @"2.png", @"3.png", @"4.png",@"5.png",@"6.png",@"7.png", @"8.png", nil]; for(int i = 0; i < images.count; ++i) { int index = (arc4random() % 8)+1; NSString *image = [NSString stringWithFormat:@"%d.png", index]; CCSprite*projectile = [CCSprite spriteWithFile:image]; //CCSprite *projectile = [CCSprite spriteWithFile:@"3.png" rect:CGRectMake(0, 0,256,256)]; [self addChild:projectile]; [movableSprites addObject:projectile]; float offsetFraction = ((float)(i+1))/(images.count+1); //projectile.position = ccp(20, winSize.height/2); //projectile.position = ccp(18,0 ); //projectile.position = ccp(350*offsetFraction, 20.0f); projectile.position = ccp(10/offsetFraction, 20.0f); // projectile.position = ccp(projectile.position.x,projectile.position.y); // Determine offset of location to projectile int offX = location.x - projectile.position.x; int offY = location.y - projectile.position.y; // Bail out if we are shooting down or backwards if (offX <= 0) return; // Ok to add now - we've double checked position //[self addChild:projectile]; // Determine where we wish to shoot the projectile to int realX = winSize.width + (projectile.contentSize.width/2); float ratio = (float) offY / (float) offX; int realY = (realX * ratio) + projectile.position.y; CGPoint realDest = ccp(realX, realY); // Determine the length of how far we're shooting int offRealX = realX - projectile.position.x; int offRealY = realY - projectile.position.y; float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY)); float velocity = 480/1; // 480pixels/1sec float realMoveDuration = length/velocity; // Move projectile to actual endpoint [projectile runAction:[CCSequence actions: [CCMoveTo actionWithDuration:realMoveDuration position:realDest], [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]]; // Add to projectiles array projectile.tag = 1; [_projectiles addObject:projectile]; } }

    Read the article

  • Crash when using Cocos2d

    - by ipodfreak0313
    Sorry about the poor question title, it's just that this seems to big for a title. So here's the dirt: I am making a game (obviously) and I want the enemies to shoot (not necessarily at the player). I want the shoot method to be in the Enemies file, so as not to clutter up my HelloWorldLayer.m file even more. Here's what I'm using right now: HelloWorldLayer.m -(void)addEnemy:(BigAndStrongEnemy *)enemy { enemy = nil; if((arc4random() % 4) == 3) { enemy = [BigAndStrongEnemy enemy]; } else { enemy = [SmallAndFastEnemy enemy]; } if(buffDude.position.y > character.position.y || buffDude.position.y < (character.position.y + 10)) { } int rand = arc4random() % 320; if((arc4random() % 2 == 1)) { [enemy setPosition:ccp(0,rand)]; }else{ [enemy setPosition:ccp(480,rand)]; } [self animateEnemy:enemy]; [self addChild:enemy]; } -(void)animateEnemy:(BigAndStrongEnemy *)enemy2 { float randX = arc4random() % 480; float randY = arc4random() % 320; int rand = arc4random() % 320; CGPoint moveToPoint = CGPointMake(randX, (randY - rand)); [enemies addObject:enemy2]; action = [CCSequence actions: [CCMoveBy actionWithDuration:1 position:ccpMult(ccpNormalize(ccpSub(moveToPoint, enemy2.position)), 75)], [CCMoveBy actionWithDuration:3 position:ccp(buffDude.position.x,buffDude.position.y)], nil]; CCCallFuncO *a = [CCCallFuncO actionWithTarget:self selector:(@selector(shoot:)) object:enemy2]; CCSequence *s = [CCSequence actions:action,a, nil]; CCRepeatForever *repeat = [CCRepeatForever actionWithAction:s]; [enemy2 runAction:repeat]; } And here's the Shoot info from the Enemies class: Enemies.m: -(void)shoot:(id)sender { self = (BigAndStrongEnemy *)sender; [self shoot]; } -(void)spriteMoveFinished:(id)sender { CCSprite *b = (CCSprite *)sender; [self removeChild:b cleanup:YES]; } -(void)shoot { self = [CCSprite spriteWithFile:@"bigAndStrongEnemy.gif"]; CCSprite *b = [CCSprite spriteWithFile:@"bullet.gif"]; b.position = ccp(self.position.x,self.position.y); b.tag = 2; [self addChild:b]; [bullets addObject:b]; CGSize winSize = [[CCDirector sharedDirector] winSize]; CGPoint point = CGPointMake((winSize.width - (winSize.width - self.position.x)),0); [b runAction:[CCSequence actions: [CCMoveBy actionWithDuration:0.5 position:point], [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]]; } Every time the 3 seconds goes by, the app crashes, and goes to the breakpoint in the CCCallFuncO file. I haven't touched it, is the thing. I am completely confused. Any help is greatly appreciated.

    Read the article

  • custom type face class by dinesh?

    - by dineshpeiris
    package typeface{ import flash.display.*; import flash.events.Event; import flash.filters.BitmapFilter; import flash.filters.BitmapFilterQuality; import flash.filters.BlurFilter; public class Main extends Sprite { private var typeSet:String="SEE > THINK > CREATE"; private var collectionSet:MovieClip; private var w:int = 1; public function Main():void { trace("start typeface application"); collectionSet = new MovieClip(); for (var n:int = 0; n < typeSet.length; n++) { var _x:int = 0 + (40 * n); var _y:int = 0; var Type:TypeCollector = new TypeCollector(_x, _y, stringToCharacter(typeSet, n), collectionSet); Type.addEventListener("action", actionHandler); } collectionSet.x = 100; collectionSet.y = (stage.stageHeight / 2) - 80; addChild(collectionSet); } private function actionHandler(event:Event):void { if (w == 16) { collectionSet.filters = [new BlurFilter(30, 30, BitmapFilterQuality.HIGH)]; removeChild(collectionSet); } w++; } public function stringToCharacter(str:String, n:int):String { if (str.length == 1) { return str; } return str.slice(n, n+1); } } } package typeface { import flash.display.*; import flash.events.Event; import flash.utils.Timer; import flash.events.TimerEvent; import flash.filters.BitmapFilter; import flash.filters.BitmapFilterQuality; import flash.filters.BlurFilter; import flash.events.EventDispatcher; public class TypeCollector extends EventDispatcher { private var TYPE_MC:typeMC; private var typeArray: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", "<", ">"); private var character:String; private var num:int = 0; private var TypeTimer:Timer; private var _xNum:int; private var _yNum:int; private var movieClip:MovieClip; public function TypeCollector(_x:int, _y:int, char:String, movie:MovieClip) { var totalNum:int = typeArray.length; _xNum = _x; _yNum = _y; movieClip = movie; character = char; TypeTimer = new Timer(100, totalNum); TypeTimer.addEventListener("timer", TypeRoutTimer); TypeTimer.start(); } public function TypeRoutTimer(event:TimerEvent):void { CreateTypeFace(num, _xNum, _yNum, character); num++; } public function CreateTypeFace(num:int, _x:int, _y:int, character:String) { if (character == " ") { } else { if (TYPE_MC != null) { TYPE_MC.filters = [new BlurFilter(30, 30, BitmapFilterQuality.HIGH)]; movieClip.removeChild(TYPE_MC); } if (typeArray[num] == character) { TYPE_MC = new typeMC(); TYPE_MC.x = _x; TYPE_MC.y = _y; TYPE_MC.typeTF.text = typeArray[num]; TYPE_MC.filters = [new BlurFilter(5, 5, BitmapFilterQuality.HIGH)]; movieClip.addChild(TYPE_MC); dispatchEvent(new Event("action")); TypeTimer.stop(); } else { TYPE_MC = new typeMC(); TYPE_MC.x = _x; TYPE_MC.y = _y; TYPE_MC.typeTF.text = typeArray[num]; TYPE_MC.filters = [new BlurFilter(10, 10, BitmapFilterQuality.HIGH)]; movieClip.addChild(TYPE_MC); } } } } }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >