26 August 2014

Super Sprite Bundle Cartoon Smart


Another September 2014 Update
Well, not a sprite pack for this update, but now it's an iOS game template. Yeah, some of my game assets are included on this Zombie game template: Hillbilly Brothers vs Zombies

http://gameartpartners.com/downloads/hillbilly-brothers-vs-zombies-and-fantastic-worlds-ios-starter-kit-bundle/?ref=1

Only $249 and you'll get full game template, from code to the graphic assets.
So, if you want to create an iOS game, especially with zombie theme, then highly probably that this game template is a good start.
Halloween is about to come, btw. So, sure, a zombie game is a good idea... :)


September 2014 Update
The 4th of The Super Sprite Bundle series released already. Well yeah, that was fast. It just a few weeks after the 3rd was released.

Nothing more to talk about, so it's 14 game asset packs for just $69. But there's a  discount on its site. Don't miss it.

 Click the image to see more details.


August 2014 Update
Alright, the third series of The Super Sprite Bundle now released. 10 items for just $49.
Check it out:

the super sprite bundle 3 cartoon smart
 Click the image to see more details.

Also, CartoonSmart now have their own game asset marketplace called GameArtPartners.com. All my game assets as well as the bundles now listed on that site. So you have plenty of choice where you'll buy my game assets.

=============

May 2014 Update.
Well, instead creating a new post for the announcement, I think it's better to merge it to the previous post.
So, to all my blog readers & visitors I want tell you that the second sprite bundle released already: The Super Sprite Bundle 2.
Don't forget to check this out:

The Super Sprite Bundle 2
Click the image to see detailed information for this pack.


=============
Just want to inform all of my blog readers and visitors, especially the ones that looking to buy my game assets, that starting on February 2014, I partnered with CartoonSmart to release my items as a bundle on their site, called The Super Sprite Bundle.
Check it out:

2d game asset super sprite bundle
Click the image to see detailed information for this pack.

As you can see, it only $39 and you get several items at once. From platformer tilesets, game GUI packs, and character spritesheets are included.
And the most importantly, it’s coming as a single license only. No need to messed up with licenses provided by marketplace sites which sometimes not quite suitable for game developers. So for anyone who looking for affordable game assets, this Sprite Bundle definitely what are you looking for.

We’re planning to release another bundle next month. See what will happen…

If it still can’t make you satisfied, well, probably we can make our own deal instead. Simply drop me a mail.

25 August 2014

My tutorials about creating menu on Citrus Engine are very outdated. The concept might be still relevant, but the code surely won’t compiled unless you have the old version of Citrus Engine. Not to mention that the old CE was only for browser game only, not mobile.

So, this time, in this article, I’ll tell you about how to build game menu on Citrus Engine, which will work on mobile, surely with the help of Starling Framework and Feathers UI, as well as some Starling Extension. Almost forget, this tutorial will also tell you how to create a simple screen transitions.

Citrus Engine Starling Feathers

Yes, we’ll do it via code, not visual editor (Flash IDE)  like on the old tutorial. But don’t worry, Starling & Feathers are very capable for creating complex UI components. So, your work is just simply placing the components on the screen.

Getting Started
Using Flash Develop, you’ll need to create a new mobile project. Yes, mobile, so you can see the result on your mobile devices. As always, I won’t explain the process, since it’s quite basic and you can get some tutorials elsewhere.

The basic idea for the game structure is similar as the old tutorial. Separate each game screen into CE states. And use the Main class as a state machine or screen manager or screen selector, well, whatever you’ll name it. Probably you can read it to get some picture about what will we achieve here.

Alright, let’s create the Main class

package    
{     
    import citrus.core.starling.StarlingCitrusEngine;
    import citrus.core.starling.StarlingState;     
    import flash.events.Event;     
    import starling.core.Starling;     
    import citrus.core.starling.ViewportMode;     
    import com.greensock.TweenLite;     
    import state.MenuState;     
  
    public class Main extends StarlingCitrusEngine     
    { 
        public function Main()     
        {     
            super();     
        }     
      
        override protected function handleAddedToStage(event:Event):void     
        {     
            super.handleAddedToStage(event);     
            
            Starling.handleLostContext = true;     
            Starling.multitouchEnabled = true;     
            
            _baseWidth = 800;     
            _baseHeight = 480;     
            
            _viewportMode = ViewportMode.LETTERBOX;     
            
            setUpStarling(true);     
        }     
        
        override public function handleStarlingReady():void     
        {     
            super.handleStarlingReady();     
           
            state = new MenuState();     
        }     
        
        public function changeState(nextState:StarlingState):void     
        {     
            futureState = nextState;     
           
            TweenLite.to(state, 1, { alpha:0, onComplete:toNewState } );     
            
            function toNewState():void     
            {     
               state = futureState;     
            }     
        }     
    }     
}

We configure the game on the handleAddedToStage() method. Set handleLostContext and multitouchEnabled to true. Google that if you need some explanations about that property.

Also set the _baseWidth and _baseHeight. And set the viewportMode to LetterBox. This means we will build the game for 800x480 devices, but the game will also nicely scaled up and down if it run on a device other than that. For clearer explanation, simply go here.


Changing States & Transition
Now take a look at changeState() method. This method will be used to change state across the game screen. The great thing is that Citrus Engine already provide a support for screen transition by creating a futureState property.

So, inside the method what we do is pass the state object from method’s argument to futureState. Then apply a transition effect to the current state. I’m using TweenLite from greensock here, but surely will also work with other tweening library. Using its alpha property so we can have a nice fading effect. And when the transition is done, then we execute the next state by passing futureState to the current state.

All done for the Main class. Let’s move to the Menu state. This class will extend from Starling state.


Creating Background
To make it more complex, I will use a tiled scrolling background instead of just a static background. And to achieve that, we need this Starling extension: Scroll Image from Tom Krecha

I'm using this tileable & simple image as the background:

Citrus Engine Menu Background


atlas = new TextureAtlas(Texture.fromBitmap(new EmbedConst.ATLAS_IMAGE()), XML(new EmbedConst.ATLAS_XML()));    

var tile:ScrollTile = new ScrollTile(atlas.getTexture(TexNameConst.BG), true);
 
bg = new ScrollImage(stage.stageWidth, stage.stageHeight);
bg.addLayer(tile);
addChild(bg);

First, we need to create atlas that hold the required texture. Then create a ScrollTile object. And pass the texture on its constructor arguments. Now we make the real backround image, using ScrollImage class, and set its size in a same size as the stage width and height. Add the previously created tile to its layer using addLayer() method. Then add the background to the stage.

Done? Not yet. To make it even prettier, let’s apply some diagonal scrolling animation. Override the update() method, and add this code:

if (bg)    
{     
        bg.tilesOffsetX += .2;     
        bg.tilesOffsetY += .2;     
}

Creating Title
Title is just a static image. So nothing to explain here.

title = new Image(atlas.getTexture(TexNameConst.TITLE));    
title.alignPivot();     
title.x = stage.stageWidth / 2;     
title.y = title.height / 2 + 50;     
addChild(title);

Creating Buttons
Since all the buttons will have similar properties, this method will save you several lines of code.

private function getButton(name:String, scale:Number = 1, hasDownTexture:Boolean = true):Button    
{     
     var up:Texture = atlas.getTexture(name);     
     var down:Texture;     
            
     if (hasDownTexture)     
     {     
          down = atlas.getTexture(name.replace("1", "2"));     
     }     
     else     
     {     
          down = null;     
     }     
            
     var button:Button = new Button(up, "", down);     
     button.name = name;     
     button.scaleX = button.scaleY = scale;     
     button.alphaWhenDisabled = 1;     
     button.scaleWhenDown = .9;     
     button.addEventListener(Event.TRIGGERED, buttonClicked);     
            
     return button;     
}

Nothing special, just define the button’s up & down textures, some properties and event listener when the buttpn clicked. 

We're using the Button class from Starling not Feathers. It's enough for our need for now.

The buttons will have two textures: when it is on normal state and when it's clicked. For example:

citrus engine game buttoncitrus engine game button



Now let create some real buttons. But before that, we’ll make a layout for that.

var layout:HorizontalLayout = new HorizontalLayout();    
layout.horizontalAlign = HorizontalLayout.HORIZONTAL_ALIGN_CENTER;     
layout.verticalAlign = HorizontalLayout.VERTICAL_ALIGN_MIDDLE;     
layout.gap = 10;

We create a horizontal layout, set it’s alignment to center for both horizontal and vertical alignment. And set the gap for each button with 10 pixels.
           
var buttonContainer:LayoutGroup = new LayoutGroup();     
buttonContainer.layout = layout;     
buttonContainer.width = 800;     
buttonContainer.height = 100;     
buttonContainer.alignPivot();     
buttonContainer.x = stage.stageWidth / 2;     
buttonContainer.y = stage.stageHeight - buttonContainer.height / 2 - 30;     
addChild(buttonContainer);

Then we’ll pass the layout to a container. Set the container size, pivot point, and position.

With this container no need to set the position of each buttons, since you already set the container position. So simply add  your buttons, and done. Your button will be perfectly arranged on the screen.

play = getButton(TexNameConst.PLAY_1);    
buttonContainer.addChild(play);     
            
score = getButton(TexNameConst.SCORE_1);     
buttonContainer.addChild(score);

All done. And here it is the full code of MenuState class.

package state   
{    
    import citrus.core.starling.StarlingState;    
    import feathers.layout.HorizontalLayout;    
    import feathers.controls.LayoutGroup;    
    import flash.desktop.NativeApplication;    
    import starling.display.Button;    
    import starling.display.DisplayObject;    
    import starling.display.Image;    
    import starling.events.Event;    
    import starling.extensions.krecha.ScrollImage;    
    import starling.extensions.krecha.ScrollTile;    
    import starling.textures.Texture;    
    import starling.textures.TextureAtlas;    
    import constant.TexNameConst;    
    import constant.EmbedConst;    
    import state.GameState;    
    
    public class MenuState extends StarlingState    
    {    
        private var atlas:TextureAtlas;    
        
        private var bg:ScrollImage;    
        
        private var title:Image;    
        
        private var play:Button;    
        private var options:Button;    
        private var score:Button;    
        private var exit:Button;    
        
        private var dispObjectArray:Vector.<DisplayObject> = new Vector.<DisplayObject>();    
        
        public function MenuState()    
        {    
            super();    
        }    
        
        override public function initialize():void    
        {    
            super.initialize();    
            
            atlas = new TextureAtlas(Texture.fromBitmap(new EmbedConst.ATLAS_IMAGE()), XML(new EmbedConst.ATLAS_XML()));    
            
            var tile:ScrollTile = new ScrollTile(atlas.getTexture(TexNameConst.BG), true);    
            
            bg = new ScrollImage(stage.stageWidth, stage.stageHeight);    
            bg.addLayer(tile);    
            addChild(bg);    
            
            title = new Image(atlas.getTexture(TexNameConst.TITLE));    
            title.alignPivot();    
            title.x = stage.stageWidth / 2;    
            title.y = title.height / 2 + 50;    
            addChild(title);    
            
            var layout:HorizontalLayout = new HorizontalLayout();    
            layout.horizontalAlign = HorizontalLayout.HORIZONTAL_ALIGN_CENTER;    
            layout.verticalAlign = HorizontalLayout.VERTICAL_ALIGN_MIDDLE;    
            layout.gap = 10;    
            
            var buttonContainer:LayoutGroup = new LayoutGroup();    
            buttonContainer.layout = layout;    
            buttonContainer.width = 800;    
            buttonContainer.height = 100;    
            buttonContainer.alignPivot();    
            buttonContainer.x = stage.stageWidth / 2;    
            buttonContainer.y = stage.stageHeight - buttonContainer.height / 2 - 30;    
            addChild(buttonContainer);    
            
            play = getButton(TexNameConst.PLAY_1);    
            buttonContainer.addChild(play);    
            
            score = getButton(TexNameConst.SCORE_1);    
            buttonContainer.addChild(score);    
            
            options = getButton(TexNameConst.OPTIONS_1);    
            buttonContainer.addChild(options);    
       
            exit = getButton(TexNameConst.EXIT_1);    
            buttonContainer.addChild(exit);    
           
            dispObjectArray.push(bg, title, buttonContainer);    
        }    
      
        override public function update(timeDelta:Number):void    
        {    
            super.update(timeDelta);    
            
            if (bg)    
            {    
                bg.tilesOffsetX += .2;    
                bg.tilesOffsetY += .2;    
            }    
        }    
        
        private function buttonClicked(event:Event):void    
        {    
            var button:String = Button(event.target).name;    
            
            switch (button)    
            {    
                case TexNameConst.PLAY_1:     
                    Main(_ce).changeState(new GameState());    
                    break;    

               
                case TexNameConst.OPTIONS_1:     
                    break;    
                
                case TexNameConst.SCORE_1:     
                    break;    
                
                case TexNameConst.EXIT_1:     
                    NativeApplication.nativeApplication.exit();    
                    break;    
            }    
        }    
        
        private function getButton(name:String, scale:Number = 1, hasDownTexture:Boolean = true):Button    
        {    
            var up:Texture = atlas.getTexture(name);    
            var down:Texture;    
            
            if (hasDownTexture)    
            {    
                down = atlas.getTexture(name.replace("1", "2"));    
            }    
            else    
            {    
                down = null;    
            }    
            
            var button:Button = new Button(up, "", down);    
            button.name = name;    
            button.scaleX = button.scaleY = scale;    
            button.alphaWhenDisabled = 1;    
            button.scaleWhenDown = .9;    
            button.addEventListener(Event.TRIGGERED, buttonClicked);    
            
            return button;    
        }    
        
        override public function destroy():void    
        {    
            for (var i:int = dispObjectArray.length - 1; i >= 0; i--)    
            {    
                removeChild(dispObjectArray[i], true);    
            }    
            
            atlas.dispose();    
            atlas = null;    
            
            super.destroy();    
        }    
    }    
}

And the result:



You can hit the play button and you’ll be moved to Game screen. Nothing much to do on the game. Buy you can see how the screen transition work. Also the in-game UI & HUD. We’ll cover that on the next article.

Source Code:

Download Source Code

Well, another shameless promotions.
If you’re looking for an UI assets for your games, then you can take a look, and probably buying from my collection here:

Casual Cartoon Game GUI Pack

RPG Fantasy Game GUI Pack

Casual Cartoon Game GUI Pack

For more packs as well as game assets other than just the GUI pack, you can go here: www.GameArt2D.com

10 March 2014

I’m enjoying diving deeper to Box2D at the moments. And now I want to share about Raycast. As well as how to make a Spiderman, Worm, or Bionic Commando-like rope swing, because it’s one of implementation of Raycast.

spider-man-meme-rope

Raycast
Raycasting is simply create a straight line between two point. Sound pretty simple, but it can be quite useful. Let say you want your AI character have a Line of Sight (LOS) function that will detect what objects are on his sight. Another example if you want to slice an object. Or probably simulate a light ray. I think it can be used on another scenario, that I haven’t discover yet.

I won’t explain about Box2D raycast feature here, as I also quite new to this thing. If you want more detailed explanation, maybe you can google that.

So this is my Ray class that wrapped Box2D raycast function and adds a feature to draw the line on the screen. Box2D debug draw doesn’t render the raycast graphic, so you need to create it by yourself.

package  
{    
    public class Ray     
    {     
        public static const RAY_CAST:String = "ray_cast";     
        public static const RAY_CAST_ONE:String = "ray_cast_one";     
        public static const RAY_CAST_ALL:String = "ray_cast_all";     
      
        public var startPoint:b2Vec2;     
        public var endPoint:b2Vec2;     
        
        public var onContact:Signal;     
        
        public var fraction:Number = 1;     
        
        public var fixture:b2Fixture;     
        public var fixtures:Vector.<b2Fixture>;     
        
        private var sprite:CitrusSprite;     
        private var shape:Shape;     
        
        private var box2D:Box2D;     
        
        private var type:String;     
        
        private var lineGraphic:Boolean = true;     
        
        public function Ray(box2D:Box2D, type:String = RAY_CAST, lineGraphic:Boolean = true)     
        {     
            this.box2D = box2D;     
            
            this.type = type;     
            this.lineGraphic = lineGraphic;     
            
            if (this.lineGraphic)     
            {     
                sprite = new CitrusSprite("raySprite");     
                CitrusEngine.getInstance().state.add(sprite);     
                
                shape = new Shape();     
            }     
            
            startPoint = new b2Vec2();     
            endPoint = new b2Vec2();     
          
            if (this.type == RAY_CAST)     
            {     
                onContact = new Signal(b2Fixture, b2Vec2, b2Vec2);     
            }     
        }     
        
        public function createRay():void     
        {     
            startPoint.x = startPoint.x / box2D.scale;     
            startPoint.y = startPoint.y / box2D.scale;     
            
            endPoint.x = endPoint.x / box2D.scale;     
            endPoint.y = endPoint.y / box2D.scale;     
            
            switch (type)     
            {     
                case RAY_CAST:     
                    box2D.world.RayCast(rayCastHandler, startPoint, endPoint);     
                    break;     
                
                case RAY_CAST_ONE:     
                    fixture = box2D.world.RayCastOne(startPoint, endPoint);     
                    break;     
                
                case RAY_CAST_ALL:     
                    fixtures = box2D.world.RayCastAll(startPoint, endPoint);     
                    break;     
            }     
            
            drawLine();     
        }     
        
        private function rayCastHandler(fixture:b2Fixture, intersection:b2Vec2, normal:b2Vec2, fraction:Number):Number     
        {     
            endPoint.x = intersection.x;     
            endPoint.y = intersection.y;     
            
            onContact.dispatch(fixture, intersection, normal);     
            
            return this.fraction;     
        }     
        
        private function drawLine():void     
        {     
            if (!lineGraphic)     
            {     
                return;     
            }     
            
            shape.graphics.clear();     
            shape.graphics.lineStyle(1);     
            shape.graphics.moveTo(startPoint.x * box2D.scale, startPoint.y * box2D.scale);     
            shape.graphics.lineTo(endPoint.x * box2D.scale, endPoint.y * box2D.scale);     
            
            sprite.view = shape;     
        }     
        
        public function destroy():void     
        {     
            if (type == RAY_CAST)     
            {     
                onContact.removeAll();     
                onContact = null;     
            }     
            
            if (lineGraphic)     
            {     
                shape = null;     
                sprite = null;     
            }     
            
            startPoint = null;     
            endPoint = null;     
        }     
    }     
}

I’m using Starling Graphic Extension here, because by default, Starling doesn’t have a graphics API that can be used to draw vector objects: line, square, circle, etc like Flash.

There are three constant, it will define what type of raycast will be used. RAY_CAST is the default, RAY_CAST_ONE will return first fixture that intersect with the ray, and RAY_CAST_ALL will return all fixtures.
Also there are two point, startPoint and the endPoint.

Fixture variable will hold a reference of the fixture returned if we use RaycastOne. And fixtures variable, a vector that hold reference of fixtures returned by RaycastAll.

Fraction is still a mystery for me. But from what I read somewhere, it’s used by the default Raycast to determine its behaviour. Set it to 0, it will stop at the first target on contact. Set it to 1 it will return all fixtures on contact. Set it to –1 it will ignore everything.

Other variables are self explanatory, I think.

Let’s jump to the createRay() method instead of the constructor, as it’s pretty clear already. In the createRay() method, it convert the startPoint and endPoint to box2D measurement, by simply divide it by box2D scale property. Then we can do the raycasting, based on the raycast type. 
The default raycast will need a callback function, RayCastHandler(). While the others aren’t.

On the rayCastHandler() method, you’ll get information about what fixture that intersect the ray, it’s intersection & normal point, and the fraction. Btw, I still don’t understand what’s fraction function parameter supposed to do. :\

I have a signal here, that will be dispatched when the ray hit something. It will contain all parameter, except fraction.

Okay, we’ve got the raycast wrapper set-up, now we need to implement it on the Hero class. I create a CustomHero class that extends CE default Hero class:

package    
{     
    public class CustomHero extends Hero     
    {     
        private var LOS:Ray;     
        
        public function CustomHero(name:String, params:Object = null)     
        {     
            super(name, params);     
            
            LOS = new Ray(_box2D);     
            LOS.fraction = 0;     
            LOS.onContact.add(LOSContactHandler);     
        }     
        
        override public function update(timeDelta:Number):void     
        {     
            super.update(timeDelta);     
            
            LOS.startPoint.x = x;     
            LOS.startPoint.y = y;     
            
            LOS.endPoint.x = x + 200;     
            LOS.endPoint.y = y;     
            
            if (_inverted)     
            {     
                LOS.endPoint.x = x - 200;     
            }     
            
            LOS.createRay();            
        }     
        
        private function LOSContactHandler(fixture:b2Fixture, intersection:b2Vec2, normal:b2Vec2):void     
        {     
            GameState(_ce.state).setText("target: " + fixture.GetBody().GetUserData().name);     
        }     
    }     
}


Simply create a Ray object called LOS. It will use the default RayCast. And set the fraction to 0, so it will return the first object that intersect with the ray.

Because we want to create a LOS, so it will need stick to the hero all the time, and have a fixed length. On the update() method, set the startPoint to the exact same position as the hero. And the add the length value (200) to the hero x position. Make sure it will also inverted when the hero facing opposite direction. Then call the createRay() function. On the LOSContactHandler(), it’ll just write the object’s name to a TextField.

An the result is something like this:


Move around, and the text field will tell you the object’s name that collide with the ray.
Btw, you can click & hold on the ceiling platform to activate the spidey rope.
How to create that? Just keep reading… Open-mouthed smile

Spiderman Swing


bio
Not Spiderman

The idea just to create a distance joint between the hero to a specified point. To get the target position, we use the raycast function. It will create a ray between hero and the mouse position. If there are a fixture being intersect with the ray, then it’s the target point.

I’ll just paste my GameState code here, with a lot of unnecessary code omitted:

package    
{     
    public class GameState extends StarlingState     
    {     
        private var jointRay:Ray;     
        
        private var jointDef:b2DistanceJointDef;     
        private var joint:b2DistanceJoint;     
        
        private var jointLine:Shape;     
        private var jointSprite:CitrusSprite;     
        
        private var mouseHold:Boolean = false;
         
        public function GameState()     
        {     
            super();     
        }     
        
        override public function initialize():void     
        {     
            super.initialize();
             
            jointRay = new Ray(box2D);     
            jointRay.fraction = 0;     
            jointRay.onContact.add(jointRayContact);         
          
            jointSprite = new CitrusSprite("jointSprite");     
            add(jointSprite);     
            
            jointLine = new Shape();
             
            stage.addEventListener(TouchEvent.TOUCH, click);     
        }     
        
        private function click(event:TouchEvent):void     
        {     
            var touch:Touch = event.getTouch(stage);     
            
            if (touch)     
            {     
                if (touch.phase == TouchPhase.BEGAN)     
                {     
                    var posX:int = event.getTouch(event.currentTarget as DisplayObject).globalX;     
                    var posY:int = event.getTouch(event.currentTarget as DisplayObject).globalY;     
                    var worldPos:Point = ((view as StarlingView).viewRoot as Sprite).globalToLocal(new Point(posX, posY));     
                    
                    var hero:CustomHero = getObjectByName("hero") as CustomHero;     
                    
                    jointRay.startPoint.x = hero.x;     
                    jointRay.startPoint.y = hero.y;     
                    jointRay.endPoint.x = worldPos.x;     
                    jointRay.endPoint.y = worldPos.y;     
                    
                    jointRay.createRay();     
                    
                    mouseHold = true;     
                }     
                else if (touch.phase == TouchPhase.ENDED)     
                {     
                    if (joint)     
                    {     
                        var box2D:Box2D = getObjectByName("box2D") as Box2D;     
                        box2D.world.DestroyJoint(joint);     
                        
                        joint = null;     
                        jointDef = null;     
                        
                        jointLine.graphics.clear();     
                    }     
                    
                    mouseHold = false;     
                }     
            }     
        }     
        
        override public function update(timeDelta:Number):void     
        {     
            super.update(timeDelta);     
            
            if (mouseHold)     
            {     
                if (joint)     
                {                    
                    var box2D:Box2D = getObjectByName("box2D") as Box2D;     
                    
                    joint.SetLength(joint.GetLength() - (5 / box2D.scale));     
                    
                    drawLine();     
                }     
            }     
        }     
        
        private function drawLine():void     
        {     
            var box2D:Box2D = getObjectByName("box2D") as Box2D;     
            
            jointLine.graphics.clear();     
            jointLine.graphics.lineStyle(2, 0xFF0000);     
            jointLine.graphics.moveTo(joint.GetAnchorA().x * box2D.scale, joint.GetAnchorA().y * box2D.scale);     
            jointLine.graphics.lineTo(joint.GetAnchorB().x * box2D.scale, joint.GetAnchorB().y * box2D.scale);     
            
            jointSprite.view = jointLine;     
        }     
        
        private function jointRayContact(fixture:b2Fixture, intersec:b2Vec2, normal:b2Vec2):void     
        {     
            var hero:CustomHero = getObjectByName("hero") as CustomHero;     
            var box2D:Box2D = getObjectByName("box2D") as Box2D;     
            
            if (joint)     
            {     
                box2D.world.DestroyJoint(joint);     
            }     
            
            jointDef = new b2DistanceJointDef();     
            jointDef.Initialize(hero.body, fixture.GetBody(), hero.body.GetWorldCenter(), intersec);     
            
            joint = box2D.world.CreateJoint(jointDef) as b2DistanceJoint;     
        }
    }    
}

Initialize all the necessary objects: Ray, DistanceJointDef, DistanceJoint. And objects for the graphical representation of the hook: Shape & CitrusSprite.
We use default RayCast mode, and fraction of 0. Don’t forget to add touch event to the stage.

Jump to the click() method. To simulate a mouse hold event on Starling we need to detect the phase. Set the mouseHold property to true when it’s in Began phase. Otherwise, set it to false when in Ended phase.

In the Began phase, we create a ray. If the ray intersect with a fixture, then surely it will fire a signal. Catch it with jointRayContact() method and create the DistanceJoint object between the hero to the intersection point.
In the Ended phase, if a joint is exists, we need to destroy them. And also remove the graphical representation.

I also shorten the rope when players holding the mouse button. Just take a look on the update() method. I reduce the joint length 5 pixel per frame. Don’t forget to divide it with box2D scale factor.

DrawLine() method, well, just to draw a red line as a graphical representation for the joint.

Done
Ok, you can download the source code here:

download

08 March 2014

Just simple tutorial for this time. I’ll show how to make a character that can aim with mouse and shoot projectiles. And I choose arrow instead of straight bullet because arrow is a little bit more advanced than bullet. But if you want your character to shoot bullet, rocket, or grenade, you can simply modify the implementation. Should be not quite much difference.

orc_archers_squad_by_daroz-d5oi7u9

Start with creating the CE project. Create MainClass and the GameState. Create floor & walls. Not much to explain here, as all of them are just default CE objects.

Open the GameState class, then inside the initialize() method, before the box2D initialization code, add this lines:

PhysicsCollisionCategories.Add("hero");    
PhysicsCollisionCategories.Add("bullet");

Since the bullet is not a sensor, we need to define a collision group for both Hero and Arrow object, so the arrow will not collide with the hero. As you can see, we create two categories, “hero” and “bullet”.

Create a new class extend CE box2D Hero class. Give it name CustomHero. After that override its defineFixture() method.

override protected function defineFixture():void  
{     
     super.defineFixture();     
            
     _fixtureDef.filter.categoryBits = PhysicsCollisionCategories.Get("hero");     
     _fixtureDef.filter.maskBits = PhysicsCollisionCategories.GetAllExcept("bullet");     
}    

We put it to ‘'hero” categories. Then maskBits is to select which object categories that can collide with this. In this case, we make the hero can collide with all objects, except any objects in the “bullet” category.

Create a new class extends CE box2D Crate class. Name it Arrow. Why extend crate? Well, I’m just lazy to create a new object from Box2DPhysicsObject class. But the arrow has quite same characteristic with crate, so why not?

public function Arrow(name:String, params:Object = null)    
{     
     super(name, params);     
            
     _beginContactCallEnabled = true;     
     updateCallEnabled = true;     
}     
        
override protected function defineFixture():void     
{     
     super.defineFixture();     
            
     _fixtureDef.density = .1;     
            
     _fixtureDef.filter.categoryBits = PhysicsCollisionCategories.Get("bullet");     
     _fixtureDef.filter.maskBits = PhysicsCollisionCategories.GetAllExcept("hero", "bullet");     
}

Inside the constructor, set both _beginContactCallEnabled & updateCallEnabled property to true. It will make the object respond when on contact. And it will enable its update() method. We also override the defineFixture() method to define its collision category things.

Shooting
Ok, move back to GameState class and now you can initialize the hero. Also make the stage respond touch input:

var hero:CustomHero = new CustomHero("hero", {width: 50, height: 80});    
hero.x = 100;     
hero.y = 100;     
add(hero);

             
stage.addEventListener(TouchEvent.TOUCH, mouseClick);

And this is what happen when you touch the screen:

private function mouseClick(event:TouchEvent):void    
{     
     var touchVec:Vector.<Touch> = event.getTouches(stage, TouchPhase.ENDED);     
            
     if (touchVec.length > 0)     
     {     
         var posX:int = event.getTouch(event.currentTarget as DisplayObject).globalX;     
         var posY:int = event.getTouch(event.currentTarget as DisplayObject).globalY;  
                 
         var worldPos:Point = ((view as StarlingView).viewRoot as Sprite).globalToLocal(new Point(posX, posY));     
                
         var hero:CustomHero = getObjectByName("hero") as CustomHero;     
                
         var angle:Number = Basic.getPointAngle(hero.x, hero.y, worldPos.x, worldPos.y);     
                
         var distX:Number = Math.abs(hero.x - worldPos.x);            
         var distY:Number = Math.abs(hero.y - worldPos.y);            
         var powerX:Number = distX / 400;     
         var powerY:Number = distY / 200;     
                
         var arrow:Arrow = new Arrow("bullet", {width: 40, height: 10});     
         arrow.x = hero.x;     
         arrow.y = hero.y;     
         arrow.rotation = Basic.radianToDegree(angle);     
         add(arrow);                
                
         var xDir:Number = Math.cos(angle) * powerX;     
         var yDir:Number = Math.sin(angle) * powerY;     
                
         arrow.body.ApplyImpulse(new b2Vec2(xDir, yDir), arrow.body.GetWorldCenter());     
     }     
}

First things first, to detect clicking or tapping, make sure there are touches that ‘ended’ already. If it’s exists then we can execute the shooting action.

We need to know the coordinates where the click happen with posX & posY variables. And then convert them to game state coordinates, worldPos Point variable.

Then get the angle between the click and you’re hero. I’m using my utility class here to do that. If you want to know how it works, there are a lot of reference about that on the web. It just calculate the x & y distance between the objects, then using atan2() to get the angle. Quite simple, but I’m too lazy to remember & rewrite it. Smile with tongue out

I designed the power of launched arrow based on the distance between the click to the hero. That’s what distX, distY, powerX, and powerY variables mean. The value of 400 & 500 on powerX and powerY are just the hardcoded one to get my desired power result.

Then we can create the arrow. Just initialize it like the other CE objects. But we need to specify its rotation using the angle we’ve got before. Convert it to degree value first. Yet again, I’m using my utility class.
Additional note: Replace the arrow object with built-in CE Missile object if you want to create a hero that shoot a straight bullet. And ignore the remaining code below.

The arrow won’t do anything for now. So let’s apply some impulse on it. Before that, define the x and y direction of the impulse, just see the xDir and yDir variables. Then using them as a vector parameter on applyImpulse() method.

Almost done. Open the Arrow class. Override the update() method:

override public function update(timeDelta:Number):void   
{    
     super.update(timeDelta);    
            
     var flyingAngle:Number=Math.atan2(body.GetLinearVelocity().y, body.GetLinearVelocity().x);    
     body.SetAngle(flyingAngle);    
}

We need to define the flyingAngle, so we’ll get a realistic flying arrow effect. Using atan2() and the arrow velocity as parameter to get the current angle.
Additional note: Remove that line, then you’ll have a stone or grenade throwing effect. Probably add a constant small rotation to get better effect.

Sticking Arrow
To get a even more realistic effect, then we can make the arrow that will stick on the target. To do that, it just using a weld joint.
Open the Arrow class, and override the handleBeginContact() method:

override public function handleBeginContact(contact:b2Contact):void   
{    
    var collider:Box2DPhysicsObject = Box2DUtils.CollisionGetOther(this, contact) as Box2DPhysicsObject;    
            
    var jointDef:b2WeldJointDef = new b2WeldJointDef();    
    jointDef.Initialize(body, collider.body, body.GetWorldCenter());    
            
    var joint:b2WeldJoint = b2WeldJoint(_box2D.world.CreateJoint(jointDef));    
            
    updateCallEnabled = false;    
            
    setTimeout(function()    
    {    
       kill = true    
    }, 2000);    
}

Take a reference to the collider, then create a weld joint between it to the arrow. Also set the updateCallEnabled to false. So it not being rotated anymore. And kill the arrow after two second hit the target using setTimeout() function.

Done
Alright, it’s done. You can see the result and download the source code below:


download

27 December 2013

Finally I managed to built a small AIR app to solve the naming problem for TiledMapEditor TMX file. Seems that I’m underestimating myself, or probably I'm just too lazy. XD

tileNamer
TMX Tile Namer… Yeah, it doesn't sound right… I’m not even sure that the term “Namer” is exist on English dictionary… XD

This is just one button app. To use, click on the button, and a browse window will appear. Then you can search for the tile atlas XML file. Open the file, wait for couple of second, then a new XML file will be created on your desktop.
Additionally, you can simply drag and drop the XML file to the button, and it will automatically generate an output XML file on your desktop.

There are some limitations in this app:
The app only work if the tiles have uniform size and make sure there are no empty tiles in the tileset. See below:

sprites

Something like tileset below won’t work as you can see, there are three empty tiles. Because TiledMapEditor will treat empty space/tile/region as a single tile, while on the atlas XML file, there are no information for that empty tiles.

sprites - Copy

To solve the problem, you can add new tiles or duplicate some of the existing tiles, so there are no empty tiles. Not a resource wise for sure. But that’s the only solution for now.

Another limitation is that the app won’t write the tile name directly to the TMX file. So, to complete the process, open this app’s output XML file, and copy all the <tile> node inside the root node <tiles>.

tileNamer2

Open the TMX file with your code editor, then paste them inside the <tileset> node

tileNamer3

Still a little bit complicated, but surely less headache than giving name to each tiles one by one via TiledMapEditor. XD

Probably in the future, I’ll improve the app. But for now, it’s enough for me.
If you want to improve the app, then here it is the app source code.
The code is messy & not commented. I’ve warn you… XD
It is a Flash CS6 project, but you can simply copy-paste or move the Main.as class to your new pure AS3 project. Flash CS6 is just used to build the interface, well, in this case it’s just a background and a button

The AIR app is inside the bin folder, named TMXTileNamer.air. Since it built with AIR 3.9, then you’ll need latest AIR runtime on your machine to install & run this app.

Well, here it is the new sample project on my previous article, but now with few more tiles added.