working on it ...

Filters

Explore Public Snippets

Sort by

Found 3 snippets

    public by leonardo  2691  2  6  0

    SNIPPET - Box2d_Java

    Codice Box2D per creare una simulazione fisica con oggetti fisici
    /*
    <SNIPPET>
    	<TAGS="JAVA,LIBGDX,BOX2D" />
    	<NAME="Box2d_Java" />
    	<DESCR>Codice Box2D per creare una simulazione fisica con oggetti fisici</DESCR>
    </SNIPPET>
    */
    
    // Codice Generico Box2D (only box2d debug mode is visible)
    
    // 100 pixels <-> 1 meter
    static final float WORLD_TO_BOX=0.01f; 
    static final float BOX_WORLD_TO=100f;
    float ConvertToBox(float x){
        return x*WORLD_TO_BOX;
    }
    
    // Step 1 - Create World
    World world=new World(new Vector2(0,-20),true) // World(Vector2 gravity, boolean doSleep) // com.badlogic.gdx.math
    
    // Step 2 - Create Body
    public void CreateBody(World world,Vector2 pos,float angle){
        BodyDef bodyDef = new BodyDef(); 
        bodyDef.type = bodyType; // The body type: static, kinematic, or dynamic
        bodyDef.position.set(ConvertToBox(pos.x),ConvertToBox(pos.y)); // The world position of the body.
        bodyDef.angle=angle; // The world angle of the body in radians.
        body = world.createBody(bodyDef);
    }
    
    // Step 3 - Create Fixture/Shape
    private void MakeRectFixture(float width,float height,BodyDef.BodyType bodyType,
         float density,float restitution, Vector2 pos,float angle){
         PolygonShape bodyShape = new PolygonShape();
    
         float w=ConvertToBox(width/2f);
         float h=ConvertToBox(height/2f);
         bodyShape.setAsBox(w,h);
    
         FixtureDef fixtureDef=new FixtureDef();
         fixtureDef.density=density; // The density, usually in kg/m^2.
         fixtureDef.restitution=restitution; // The restitution (elasticity) usually in the range [0,1].
         fixtureDef.shape=bodyShape;
         /*
         com.badlogic.gdx.physics.box2d.Shape
    		com.badlogic.gdx.physics.box2d.PolygonShape {ChainShape, CircleShape, EdgeShape, PolygonShape}
    			PolygonShape (->setAsBox(float hx, float hy) Build vertices to represent an axis-aligned box.)
         */
    
         body.createFixture(fixtureDef);
         bodyShape.dispose(); // lo puoi fare perchè la shape è clonata quando viene assegnata alla fixture
     }
    
    private void MakeCircleFixture(float radius,BodyDef.BodyType bodyType,
         float density,float restitution, Vector2 pos,float angle){
    
         FixtureDef fixtureDef=new FixtureDef();
         fixtureDef.density=density;
         fixtureDef.restitution=restitution;
         fixtureDef.shape=new CircleShape();
         fixtureDef.shape.setRadius(BoxObjectManager.ConvertToBox(radius));
    
         body.createFixture(fixtureDef);
         fixtureDef.shape.dispose();
     }
    
    // Step 4 - World Update Fixed TimeStep
    static final float BOX_STEP=1/120f;
    static final int  BOX_VELOCITY_ITERATIONS=8;
    static final int BOX_POSITION_ITERATIONS=3;
    float accumulator;
    
    public void Update(float dt){
       accumulator+=dt;
        while(accumulator>BOX_STEP){
          world.step(BOX_STEP,BOX_VELOCITY_ITERATIONS,BOX_POSITION_ITERATIONS);
          accumulator-=BOX_STEP;
       }
    
    }
    
    

    public by leonardo  2124  3  6  0

    GUIDE - Javascript

    ------------------------------------------------------------
    JAVASCRIPT
    ------------------------------------------------------------
    References:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
    
    1. Objects
    ----------
    
    	1.1 Core Objects
    	----------------
    	https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
    
    	Math, Object, Array, and String
    
    	1.2 Custom Objects
    	------------------
    
    		1.2.1 Creating Custom Objects
    		-----------------------------
    
    			1.2.1.1 Creating objects using new Object() [not flexible]
    			----------------------------------------------------------
    
    			person = new Object()
    			person.name = "Tim Scarfe"
    			person.height = "6Ft"
    
    			person.run = function() {
    				this.state = "running"
    				this.speed = "4ms^-1"
    			}
    
    			1.2.1.2 Creating objects using Literal Notation [not flexible]
    			--------------------------------------------------------------
    
    			timObject = {
    				property1 : "Hello",
    				property2 : "MmmMMm",
    				property3 : ["mmm", 2, 3, 6, "kkk"],
    				method1 : function(){alert("Method had been called" + this.property1)}
    			};
    
    			timObject.method1();
    			alert(timObject.property3[2]) // will yield 3
    
    			var circle = { x : 0, y : 0, radius: 2 } // another example
    
    			// nesting is no problem.
    			var rectangle = { 
    				upperLeft : { x : 2, y : 2 },
    				lowerRight : { x : 4, y : 4}
    			}
    
    			alert(rectangle.upperLeft.x) // will yield 2
    
    			1.2.1.3 Object Constructor Function
    			-----------------------------------
    
    			An object constructor is merely a regular JavaScript function, so it's just as robust (ie: define parameters, call other functions etc). The difference between the two is that a constructor function is called via the new operator.
    
    			function cat(name) {
    				this.name = name;
    				this.talk = function() {
    					alert( this.name + " say meeow!" )
    				}
    			} 
    
    			cat1 = new cat("felix")
    			cat1.talk() //alerts "felix says meeow!"
    
    			cat2 = new cat("ginger")
    			cat2.talk() //alerts "ginger says meeow!"
    
    			A questo oggetto possiamo aggiungere metodi tramite il prototype
    
    			cat.prototype.changeName = function(name) {
    				this.name = name;
    			}
    
    			firstCat = new cat("pursur")
    			firstCat.changeName("Bill")
    			firstCat.talk() //alerts "Bill says meeow!"
    
    		1.2.2 Subclasses and Superclasses
    		---------------------------------
    		...
    
    		1.2.3 Objects as Associative Arrays
    		-----------------------------------
    
    		// These are the same
    		  object.property
    		  object["property"]
    
    		NOTA: come in LUA
    
    		1.2.4 Calling Methods
    		---------------------
    
    		We can set this explicitly using Function#call (or Function#apply)
    		Rif: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
    		Rif: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply
    
    		function Person(firstName) {
    		  this.firstName = firstName;
    		}
    
    		Person.prototype.sayHello = function() {
    		  alert("Hello, I'm " + this.firstName);
    		};
    
    		var person1 = new Person("Alice");
    		var helloFunction = person1.sayHello;
    
    		helloFunction.call(person1);                        // alerts "Hello, I'm Alice"
    
    
    
    
    2. Namespaces in Javascript
    ---------------------------
    
    Let's create a global object called MYAPP:
    
    // global namespace
    var MYAPP = MYAPP || {};
    
    

    public by leonardo  3814  1  5  -1

    GUIDE - SpriteKit

    ###############################################################################################
    # CLASSES AND METHODS
    ###############################################################################################
    
    SKVIEW
        - [skView presentScene:scene];
    
    SKSCENE
        -(id)initWithSize:(CGSize)size
    
    ###############################################################################################
    # BEST PRACTICE AND TOOLTIPS
    ###############################################################################################
    
    /*
    The following code is wrong, because the method:
    viewDidLoad is called immediately after loading your nib.  
    It hasn't even added the view to the view hierarchy yet. 
    So it hasn't resized your view based on the device's rotation either.
    When viewDidLoad is called, this is before the view has been added to the 
    view hierarchy and hence it hasn’t responded to layout changes yet!!
    
    */
    - (void)viewDidLoad
    {
        [super viewDidLoad];
     
        // Configure the view.
        SKView * skView = (SKView *)self.view;
        skView.showsFPS = YES;
        skView.showsNodeCount = YES;
     
        // Create and configure the scene.
        SKScene * scene = [MyScene sceneWithSize:skView.bounds.size];
        scene.scaleMode = SKSceneScaleModeAspectFill;
     
        // Present the scene.
        [skView presentScene:scene];
    }
    
    /*
    Solution:
    Replace viewDidLoad with the following:
    */
    - (void)viewWillLayoutSubviews
    {
        [super viewWillLayoutSubviews];
     
        // Configure the view.
        SKView * skView = (SKView *)self.view;
        if (!skView.scene) {
          skView.showsFPS = YES;
          skView.showsNodeCount = YES;
     
          // Create and configure the scene.
          SKScene * scene = [MyScene sceneWithSize:skView.bounds.size];
          scene.scaleMode = SKSceneScaleModeAspectFill;
     
          // Present the scene.
          [skView presentScene:scene];
        }
    }
    
    
    ######### Implementing RUNACTION WITHKEY WITH COMPLETION (no method in official API)
    
    SKAction *yourAction = ...
    
    SKAction *completion = [SkAction runBlock:^{
        // Your code.
    }];
    SKAction *sequence = [SKAction sequence:@[ yourAction, completion ]];
    
    [node runAction:sequence withKey:yourKey];
    
    If you use this multiple times, create SKNode category with such method:
    
    - (void)runAction:(SKAction *)action withKey:(NSString *)key completion:(void(^)(void))block;
    
    
    
    ###############################################################################################
    # PHYSICS
    ###############################################################################################
    
    ## enable contact detection:
    
    assign to property 'contactDelegate' of SKScene.physicsWorld a class that implemens the protocol <SKPhysicsContactDelegate> that
    has following interface:
    – didBeginContact:  
    – didEndContact: 
    
    ## create physical objects:
    
    just create a SKPhysicsBody and assign that to the property physicsBody of desired SKNode.
        - The physicbody can have following shapes:
            - circle
            - rectangle
            - union of existing bodies
            - polygonal path
    
    ## create an edge bound:
    
    In SKScene (that inherits from SKNode) set a physicsBody with the method + bodyWithEdgeLoopFromRect: with the scene size.
    
    ## maskbits typology for interaction between physical objects:
    
    SKPhysicBody
        - categoryBitMask (A mask that defines which categories this physics body belongs to)
        - collisionBitMask (A mask that defines which categories of physics bodies can collide with this physics body)
        - contactTestBitMask (A mask that defines which categories of bodies cause intersection notifications with this physics body)
    
    
    
    ## methods:
    
    // managing generated contact
    - (void)didBeginContact:(SKPhysicsContact *)contact
    {
        // Ordino gli oggetti per categoria, così dopo filtro più velocemente
        SKPhysicsBody *firstBody, *secondBody;
     
        if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
        {
            firstBody = contact.bodyA;
            secondBody = contact.bodyB;
        }
        else
        {
            firstBody = contact.bodyB;
            secondBody = contact.bodyA;
        }
     
        // Lancio la gestore del contatto a seconda del tipo di oggetti
        if ((firstBody.categoryBitMask & projectileCategory) != 0 &&
            (secondBody.categoryBitMask & monsterCategory) != 0)
        {
            [self projectile:(SKSpriteNode *) firstBody.node didCollideWithMonster:(SKSpriteNode *) secondBody.node];
        }
    }
    
    ###############################################################################################
    # ASSETS HANDLING
    ###############################################################################################
    
    Examples of two version of the image for normal and retina display (not 100% sure about it):
    nome@2x.png 64x72
    nome.png    32x36
    
    ASSETS ORGANIZATION
    
    - SpriteKit
    
        <description>.atlas (images here are automaticaliy inserted in a texture atlas)
            NOTA: huge images (es. big buttons or backgrounds) better if not inserted in a texture atlas (in xcode project insert only the nn@2x version ???)
            NOTA: also images that you will later use from UIKit controls (UIKit controls cannot access images inside texture atlases).
            NOTA: you make 2 version of the same image in folder .atlas: es. Tile_1.png e Tile_1@2x.png (double res)
    
    MASKS IN SPRITEKIT
    
    todo...
    
    MASKS IN CORONA SDK
    
    todo...
    
    ##########################
    # POSITIONING IN SPRITEKIT
    ##########################
    
    SKNode
        - position: The position of the node in its parent's coordinate system.
    
    SKSpriteNode
        - anchorPoint (in unit coordinates): Defines the point in the sprite that corresponds to the node’s position.
    
    
    ###############################################################################################
    # REFERENCES
    ###############################################################################################
    
    tools:
    http://dazchong.com/spritekit/ [creation of CGPath directly on the png image!]
    
    api reference
    SKNode      https://developer.apple.com/library/mac/documentation/SpriteKit/Reference/SKNode_Ref/Reference/Reference.html
    SKAction    https://developer.apple.com/library/mac/documentation/SpriteKit/Reference/SKAction_Ref/Reference/Reference.html#//apple_ref/doc/c_ref/SKAction

    List Complete ( 3 snippets total )

    • Public Snippets
    • Channels Snippets