Impact

This forum is read only and just serves as an archive. If you have any questions, please post them on github.com/phoboslab/impact

1 decade ago by dominic

I already posted this into the Games forum, but now we have new place where we can post our plugins and code snippets for Impact :)

So here is my Box2D plugin on github:

https://github.com/phoboslab/impact-box2d

Also see the Jetpack Demo and the Physics with Box2D Tutorial

1 decade ago by MobileMark

Hey Dom, I've been using Box2D and it's working great but I can't figure out a couple of things.

How can you use Collision detection with Box2D in ImpactJS to fire functions?( I can't seem to get b2.contactlistener to work)

And is it possible to have round entities in ImpactJS? (Interact as a ball)

1 decade ago by ape

I'm trying to understand how to create polygon based entities properly.

One thing I'm stuck with is figuring out how to draw the shapes so that I can verify if I've indeed succeeded in creating these polygons

Here's what I'm trying to do:

/* In my entity class I override createBody... */

createBody: function() {
      var bodyDef = new b2.BodyDef();
      bodyDef.position.Set(
        (this.pos.x + this.size.x / 2) * b2.SCALE,
        (this.pos.y) * b2.SCALE
      );

      this.body = ig.world.CreateBody(bodyDef);
      
      /* make a triangle */
      var shapeDef = new b2.PolygonDef();
      shapeDef.vertexCount = 3;
      shapeDef.vertices[0].Set(-1.0, 0.0);
      shapeDef.vertices[1].Set(1.0, 0.0);
      shapeDef.vertices[2].Set(0.0, 1.0);
      
      shapeDef.density = 1;
      shapeDef.friction = 0.9;
      this.body.CreateShape(shapeDef);
      this.body.SetMassFromShapes();
      
      /* see if I can draw its shape */
      var debugDraw = new b2.DebugDraw();
     
      /* this is where I get stuck - what does it need as a sprite? */
      debugDraw.m_sprite = this;
      debugDraw.m_drawScale = b2.SCALE;
      debugDraw.SetFlags(b2.DebugDraw.e_shapeBit);
      debugDraw.m_lineThickness = 2.0;
      debugDraw.m_fillAlpha = 0.6;
      ig.world.SetDebugDraw(debugDraw);
      
    },

I think I'm nearly there but I'm stuck at supplying the debugDraw object with a "sprite". If this were Flash, a sprite would be simply a Sprite. An object it'd draw the polygon on. That doesn't translate well in JS.

I did see this in the JS Box2D lib but I'm feeling a bit dense. I get the idea that it's simulating a Flash sprite by saying that m_sprite is the debugDraw object's Canvas context. However, if you leave debugDraw.m_sprite empty, it complains. If you give debugDraw.m_sprite this as I've done above, it complains.

Stumped!

EDIT: including the Box2D js code I was referring to in the last paragraph:

b2DebugDraw.b2DebugDraw = function () {
      this.m_drawScale = 1.0;
      this.m_lineThickness = 1.0;
      this.m_alpha = 1.0;
      this.m_fillAlpha = 1.0;
      this.m_xformScale = 1.0;
      var __this = this;
      //#WORKAROUND
      this.m_sprite = {graphics: {clear: 
         function() {__this.m_ctx.clearRect(0,0,__this.m_ctx.canvas.width,__this.m_ctx.canvas.height)}
      }};
   };

1 decade ago by ape

I made some progress on my problem. Rather than rely on the Box2D to draw polygons, I do it myself in the draw method for my Entity.

createBody: function() {
    var bodyDef = new b2.BodyDef();
    
    bodyDef.position.Set(
      (this.pos.x + this.size.x / 2) * b2.SCALE,
      (this.pos.y + this.size.y / 2) * b2.SCALE
    );
    
    this.body = ig.world.CreateBody(bodyDef);
    
    var b = this.size.x / 2 * b2.SCALE;
    var c = this.size.y / 2 * b2.SCALE;
    
    this.shapeDef = new b2.PolygonDef();
    this.shapeDef.vertexCount = 3;
    this.shapeDef.vertices[0].Set(-b, -c);
    this.shapeDef.vertices[1].Set(b, -c);
    this.shapeDef.vertices[2].Set(b, c);
    
    this.shapeDef.density = 1.0;
    this.shapeDef.friction = 1.0;
    this.body.CreateShape(this.shapeDef);
    this.body.SetMassFromShapes();
  },
  draw: function() {
    this.parent();
    var canvas= ig.system.canvas;
    var context=canvas.getContext("2d");

    var tempCanvas=document.getElementById("tmpCanvas"); //ig.$new('canvas');
    var tempContext=tempCanvas.getContext("2d");

    var x = (this.pos.x);
    var y = (this.pos.y);
    var centerX = x/2;
    var centerY = y/2;
    
    tempContext.clearRect(0,0,canvas.width,canvas.height);
    tempContext.beginPath();
    tempContext.moveTo(x, y);
    tempContext.lineTo(x+this.size.x, y+this.size.x);
    tempContext.lineTo(x, y+this.size.x);
    tempContext.fillStyle="red";
    tempContext.fill();
    tempContext.closePath();
    tempContext.globalCompositeOperation="source-over"; 
    context.drawImage(tempCanvas, 0, 0);
  },

This sort of works.

To work, I need to have a hidden canvas element in my index.html file with an id of "tmpCanvas", the width of both canvas elements must be identical, and the scale of the game must be set to 1. I'm sure there's a simple reason why - my brain is just too fried to figure it out.

Also, and most importantly, I can't get rotation of the polygon to work properly. Since the tempContext object is the same size as the entire canvas, when rotating it rotates around the center of a huge rectangle, rather than the very tiny triangle.

I'll try figuring out how to use a smaller temporary canvas (or do away with that requirement entirely).

1 decade ago by dominic

Okay, I experimented a bit with contacts and contact listeners. Here's the thing: Contact Listeners are global for your whole world. You don't attach a contact listener to just one body, but to the world for all bodies. Here's an example for that. But read on - I found a simpler way to do this!

// Subclass the b2.ContactListener
var myListenerClass = function(){};
myListenerClass.prototype = new b2.ContactListener();

// Define your listener functions 
myListenerClass.prototype.Add = function( points ) {
	console.log( 
		'contact added',
		points.shape1.GetBody(),
		points.shape2.GetBody()
	);
};

myListenerClass.prototype.Remove = function( points ) {
	console.log( 
		'contact removed',
		points.shape1.GetBody(),
		points.shape2.GetBody()
	);
};

// Create the listener and attach it to the world
var myListener = new myListenerClass();
ig.world.SetContactListener( myListener );

You could then figure out to which entity this shape/body belongs to by attaching some user data. See Box2D Manual - User Data.


Now, here's a simpler way I found: When you just want to check if, for instance, the player entity is standing on the ground, you can iterate over all contacts that the box2d body for this entity currently has. E.g. in your entity's update() method:

update: function() {
	// Iterate over all contact edges for this body. m_contactList is 
	// a linked list, not an array, hence the "funny" way of iterating 
	// over it
	for( var edge = this.body.m_contactList; edge; edge = edge.next ) {
		
		// Get the normal vector for this contact
		var normal = edge.contact.m_manifold.normal;
		
		// If the normal vector for this contact is pointing upwards
		// (y is less than 0), then this body is "standing" on something
		if( normal.y < 0 ) {
			console.log( 'standing!' );
		}				
	}
	
	…
}

Hope that helps!

I'll experiment a bit more with different shapes in box2d this weekend and report my findings :)

1 decade ago by MobileMark

Any progress on different shapes? I've been pulling my hair out trying to figure this out

1 decade ago by dominic

Sorry Mark, totally forgot about this :/

Ok, I added a new class to the Box2D plugin that enables debug drawing through Box2D's own draw functions. Get it from Github (only debug.js and lib.js have been updated):
https://github.com/phoboslab/impact-box2d

Require plugins.box2d.debug and use it like this:

init: function() {
	…
	// In your game's init() method, after the Box2d world has 
	// been created (e.g. after .loadLevel())
	this.debugDrawer = new ig.Box2DDebug( ig.world );
},

draw: function() {
	// Draw your game first
	this.parent(); 
	
	// Then draw the Box2d debug stuff
	this.debugDrawer.draw();
}

With the debug drawing ready, creating shapes other than simple boxes should be a lot easier. You can finally see what you're doing :) Here's an example how to create circle shapes:

// In your entity class
createBody: function() {		
	var bodyDef = new b2.BodyDef();
	bodyDef.position.Set(
		(this.pos.x + this.size.x / 2) * b2.SCALE,
		(this.pos.y + this.size.y / 2) * b2.SCALE
	);
		
	this.body = ig.world.CreateBody(bodyDef);

	// These two lines define the shape
	// e.g. b2.PolygonDef, b2.CircleDef
	var shapeDef = new b2.CircleDef();
	shapeDef.radius = 8 * b2.SCALE;
		
	shapeDef.density = 1;
	this.body.CreateShape(shapeDef);
	this.body.SetMassFromShapes();	
},

Obligatory screenshot:
/>			</div>
		</div>
			<div class=

1 decade ago by MobileMark

Thanks so much! Works great

1 decade ago by MobileMark

Hey Dom, I'm having one hell of a time with collision detection in Box2D. I modified your code above so that I have something like this:

myListenerClass.prototype.Add = function( points ) {
		   
			var body1 = points.shape1.GetBody();
			var body2 = points.shape2.GetBody();
			
			var body1val=body1.m_userData!=null?body1.m_userData.indexOf("GHOST||"):null;
			var body2val=body2.m_userData!=null?body2.m_userData.indexOf("GHOST||"):null;
			
			if(body1val>-1&&body2.m_userData==null||body2val>-1&&body1.m_userData==null)
			{
				if(body1val!=null&&body1val>-1)
				    {var valInd=parseInt(body1.m_userData.split("GHOST||")[1])-1;}
				else
					{var valInd=parseInt(body2.m_userData.split("GHOST||")[1])-1;}
				
				if(ig.game.entities[valInd])
				{	
				
					if(ig.game.entities[valInd].currentAnim == ig.game.entities[valInd].anims.dead)
					{}
					else
					{ig.game.entities[valInd].currentAnim = ig.game.entities[valInd].anims.dead;}
				
				}
			}
			
		};
	
		var myListener = new myListenerClass(this.body.m_userData);
		ig.world.SetContactListener( myListener );

This works only half of the time and I'm assuming I'm doing a lot more work then I need to. Is there an easier way to detect when an Entity has hit the ground or another Entitiy?

1 decade ago by bionur

Hey Hi Dom concerning ur way of solving the contact of the player with the ground, i tried to use that in my demo game where the player can jump and run as well. I have one boolean flag that is set to true or false depending on the normal.y u offered. U know i get really funny result i tried to find the logic error but failed. The problem is that when i jump first time it doesnt jump but if i jump while processing first jump it works really buggy. Would appreciate if u could help me out with it. Honestly i have never used javascript hardcore before so would also appreciate if u could give more details where i could implement contactListener. Is it in my entity.js or should i do that in my own player.js entity really puzzled? here i am attaching a cod snippet from my update function:

update: function() {
//var currentPos;


for( var edge = this.body.m_contactList; edge; edge = edge.next ) {

// Get the normal vector for this contact
var normal = edge.contact.m_manifold.normal;

// If the normal vector for this contact is pointing upwards
// (y is less than 0), then this body is "standing" on something
if( normal.y < 0 ) {
this.inAir = false;
console.log("standing");
//break;
}
}

if( ig.input.state('runRight') ) {

//this.vel.x = this.vel.x + 400;
this.body.ApplyImpulse(new b2.Vec2(25,0), this.body.GetPosition());
this.flip = false;
this.moved = true;
if(!this.inAir){
console.log("inside runRight");
this.currentAnim = this.anims.run;
}

//this.currentPos = this.body.GetPosition();


}else if( ig.input.state('runLeft')){
//this.vel.x = this.vel.x - 400;
this.body.ApplyImpulse(new b2.Vec2(-25,0), this.body.GetPosition());

this.flip = true;
this.moved = true;
if(!this.inAir){
console.log("inside runLeft");
this.currentAnim = this.anims.run;
}

//this.currentPos = this.body.GetPosition();
}

else if(!this.inAir){
this.currentAnim = this.anims.idle;
//this.vel.x = 0;
console.log("inside idle");
this.body.SetLinearVelocity(new b2.Vec2(0,0));


}

if(ig.input.pressed('jump') && !this.inAir){
//this.accel.y = 0;
//this.vel.y = -200;
console.log("inside jump");
this.currentAnim = this.anims.jump;
this.body.ApplyImpulse(new b2.Vec2(0,-1600), this.body.GetPosition());
this.inAir = true;

}


/*else if(this.inAir && !(ig.input.pressed('jump'))){
this.body.ApplyImpulse(new b2.Vec2(0, 400), this.body.GetPosition());
this.currentAnim = this.anims.fall;
this.inAir = false;
}*/

/*if(this.vel.y < 0){
this.currentAnim = this.anims.jump;
}else if(this.vel.y > 0){
this.currentAnim = this.anims.fall;
}else if(this.vel.x != 0){
this.currentAnim = this.anims.run;
}else{
this.currentAnim = this.anims.idle;
}*/

this.currentAnim.flip.x = this.flip;
this.body.SetXForm(this.body.GetPosition(), 0);

this.parent();
}

1 decade ago by SpaceHorse

>to bionur
man. use formatting when u post teh code. it's kinda tuff to read otherwise.

1 decade ago by bionur

sorry matey

1 decade ago by TylerAppmobi

bionur, you can edit your code that you previously posted (above) by selecting edit that is located next to the post title when you scroll over it. Then if you add ## before and after the code snippet, it'll be formatted correctly.

example:

if(this.code==awesome){ alert("sweet")}

1 decade ago by Zetaphor

+1 to bionur's poorly formatted question :-)

1 decade ago by pm99

i wish i could code like you guys....

but wondering if there are some 'draw' tools that one could jus draw an entity and give it it's physics parameters? Or maybe it's already available?

1 decade ago by edit /

Hey guys,
can anyone give a brief description on how to implement that above code from Dominic (10 mths ago). JS newbie.

From the tutorials I gather, I create a new 'ball.js' file.
Create my 'entities.ball' module in ball.js,
Then declare ball.js as a require?

ig.module(
'game.entities.ball'
)
.requires(
'plugins.dbox2d.entity'
)

.defines(function(){

EntityBall = ig.Box2DEntity.extend({

// size: {x: 8, y: 8},

// how come we dont use the below for collision detection?

// type: ig.Entity.TYPE.B,
// checkAgainst: ig.Entity.TYPE.NONE,
// collides: ig.Entity.COLLIDES.NEVER,


createBody: function() {
var bodyDef = new b2.BodyDef();
bodyDef.position.Set(
(this.pos.x + this.size.x / 2) * b2.SCALE,
(this.pos.y + this.size.y / 2) * b2.SCALE
);

this.body = ig.world.CreateBody(bodyDef);

// These two lines define the shape
// e.g. b2.PolygonDef, b2.CircleDef
var shapeDef = new b2.CircleDef();
shapeDef.radius = 8 * b2.SCALE;

shapeDef.density = 1;
this.body.CreateShape(shapeDef);
this.body.SetMassFromShapes();
}
});
});

1 decade ago by pm99

_Quote from _
Hey guys,
can anyone give a brief description on how to implement that above code from Dominic (10 mths ago). JS newbie.

From the tutorials I gather, I create a new 'ball.js' file.
Create my 'entities.ball' module in ball.js,
Then declare ball.js as a require?

ig.module(
	'game.entities.ball'
)
.requires(
	'plugins.dbox2d.entity'
)

.defines(function(){

EntityBall = ig.Box2DEntity.extend({

//      size: {x: 8, y: 8},
	
//      how come we dont use the below for collision detection?

//	type: ig.Entity.TYPE.B,
//	checkAgainst: ig.Entity.TYPE.NONE,
//	collides: ig.Entity.COLLIDES.NEVER,


createBody: function() {        
    var bodyDef = new b2.BodyDef();
    bodyDef.position.Set(
        (this.pos.x + this.size.x / 2) * b2.SCALE,
        (this.pos.y + this.size.y / 2) * b2.SCALE
    );
        
    this.body = ig.world.CreateBody(bodyDef);

    // These two lines define the shape
    // e.g. b2.PolygonDef, b2.CircleDef
    var shapeDef = new b2.CircleDef();
    shapeDef.radius = 8 * b2.SCALE;
        
    shapeDef.density = 1;
    this.body.CreateShape(shapeDef);
    this.body.SetMassFromShapes();    
                        }
});
});

1 decade ago by pm99

wondering if anyone else got Dominic's ball example above working?
Seems simple.. or atleast should be.

would anyone that has succeeded, want to take a stab at explaining step by step what needs to be done?

(side note: Hi Dom, wondering if you have any plans to make impactjs stupid simple so one can simply drag shapes onto our canvas, attach the necessary asset, resize as required and off to the races?). Right now, it's not that easy to create a simple rolling ball for some like me. : (

Thanks!

1 decade ago by Arantor

Quote from pm99
(side note: Hi Dom, wondering if you have any plans to make impactjs stupid simple so one can simply drag shapes onto our canvas, attach the necessary asset, resize as required and off to the races?). Right now, it's not that easy to create a simple rolling ball for some like me. : (


The problem with 'stupid simple' systems is the same that every single platform that's tried it before: they make it much, much harder to actually do anything that isn't simple, because you're having to fight the system.

Even going back to SEUCK in the late 1980s, through the likes of Klik 'n' Play and The Games Factory, each time the same thing happens: if you want to make something that fits inside some arbitrary rules, you're away, but the minute you want anything more complex, you're stuck inside a box.

Earlier this week for example I was playing around with making a canvas-based paint package using Impact to handle some of the heavy lifting, I doubt I'd be able to do that with a library made 'simple'.

Also, speaking from experience, it's actually much better to get your hands dirty, because when something weird happens, you'll be able to see why it's happening rather than seeing it buried inside some layers of a framework somewhere.

1 decade ago by pm99

Quote from Arantor
The problem with 'stupid simple' systems is the same that every single platform that's tried it before: they make it much, much harder to actually do anything that isn't simple, because you're having to fight the system.
.....
Also, speaking from experience, it's actually much better to get your hands dirty, because when something weird happens, you'll be able to see why it's happening rather than seeing it buried inside some layers of a framework somewhere.


Thanks Arantor. Well put. I agree with getting hands dirty. I just finished Javascript for Dummies. It helped me with some syntax and DOM so now I am better able to read code. Writing code is another thing. : )

I still can't get my ball entity to work. I've managed to get my ball as an entity option in weltmeister, but there is no ball visible when I go to select it to place in my game.

1 decade ago by Arantor

So what does the ball entity contain? Is an animSheet added?

1 decade ago by quidmonkey

Are you including the plugins.box2d.debug module?

1 decade ago by pm99

@Arantor,
Yes, I've basically kept what was in crate.js, as in...

animSheet: new ig.AnimationSheet( 'media/crate.png', 8, 8 ),

@quidmonkey
from https://github.com/phoboslab/impact-box2d, the readme says...
"Copy the box2d directory into your lib/plugins/ directory and require the plugins.box2d.entity and plugins.box2d.game files. Subclass your game from ig.Box2DGame and your entities from ig.Box2DEntity:"

So I had added the box2d directory and required 'plugins.box2d.entity' and 'plugins.box2d.game' but not 'plugins.box2d.debug'. I did now, but the game still won't load.

I'm confused about whether to need to use the 'box2d' folder as suggested above or the default 'dbox2d' which as overlapping js files like 'entity.js and game.js' but not 'lib.js' and 'debug.js'. Presumably the former two, entity and game js files are identitical?

I've reattached my two files. 1. Main.js and 2. ball.js and perhaps you can see where I've gone wrong?

1. main.js
ig.module( 
	'game.main' 
)
.requires(
	'impact.game',
	'impact.font',
	'plugins.dc.dc',
	'plugins.dbox2d.dbox2d',
	'game.entities.player',
	'game.entities.crate',
	'plugins.box2d.entity',
	'plugins.box2d.game',
	'plugins.box2d.debug',
	'game.entities.ball',
	'game.levels.test'
)
.defines(function(){

MyGame = ig.Box2DGame.extend({
	
	gravity: 100, // All entities are affected by this
	
	// Load a font
	font: new ig.Font( 'media/04b03.font.png' ),
	clearColor: '#1b2026',
	paused: false,
	
	init: function() {
		// bind keys for desktop web
		//ig.input.bind(ig.KEY.SPACE, 'jump');
		//ig.input.bind(ig.KEY.LEFT_ARROW, 'left');
		//ig.input.bind(ig.KEY.RIGHT_ARROW, 'right');
		//ig.input.bind(ig.KEY.F, 'shoot');
	
		this.loadLevel( LevelTest );
		AppMobi.webview.execute('canvasInit();');
		
		// -------------------
		// begin from http://impactjs.com/forums/code/box2d-plugin
		// In your game's init() method, after the Box2d world has 
		// been created (e.g. after .loadLevel())
		this.debugDrawer = new ig.Box2DDebug( ig.world );
		// end from http://impactjs.com/forums/code/box2d-plugin
		// ---------------------
	},
	
	loadLevel: function( data ) {
		this.parent( data );
		for( var i = 0; i < this.backgroundMaps.length; i++ ) {
			this.backgroundMaps[i].preRender = true;
		}
	},
	
	update: function() {		
		// screen follows the player
		var player = this.getEntitiesByType( EntityPlayer )[0];
		if( player ) {
			this.screen.x = player.pos.x - ig.system.width/2;
			this.screen.y = player.pos.y - ig.system.height/2;
		}
		
		// Update all entities and BackgroundMaps
		this.parent();
	},
	
	draw: function() {
		// Draw all entities and BackgroundMaps
		this.parent();
		
		// ---------------------
		// begin from web page http://impactjs.com/forums/code/box2d-plugin
		// Then draw the Box2d debug stuff
		this.debugDrawer.draw();
		// end from http://impactjs.com/forums/code/box2d-plugin
		// ---------------------
		
		if( !ig.ua.mobile || (typeof top != "undefined" && top.location.href.match('^http://localhost:58888')!=null)) {
			this.font.draw( 'Left/Right/Jump: Arrow Keys, F to shoot', 2, 2 );
		}
	},
	
	pause: function() {
		if (ig.system) {
			if(ig.game){
				ig.game.font.draw('Game Paused',ig.system.width/2,ig.system.height/2,ig.Font.ALIGN.CENTER);			
			}
			ig.system.stopRunLoop.call(ig.system);
		}
	},
	
	unpause: function() {
		if (ig.system ) {
			ig.system.startRunLoop.call(ig.system);
		}
	}
	
});

// Start the Game with 60fps, scaled up by a factor of 2 or 4
// Set height/width/scale based on device type
if(ig.ua.iPad){ig.main( '#_cvs', MyGame, 60, 256, 187, 4 );}
else{ig.main( '#_cvs', MyGame, 60, 240, 150, 2 );}

});

2. ball.js

ig.module(
	'game.entities.ball'
)
.requires(
	'plugins.dbox2d.entity'
)
.defines(function(){

EntityBall = ig.Box2DEntity.extend({
	size: {x: 16, y: 16},
	
	type: ig.Entity.TYPE.B,
	checkAgainst: ig.Entity.TYPE.NONE,
	collides: ig.Entity.COLLIDES.NEVER,
	
	animSheet: new ig.AnimationSheet( 'media/crate.png', 8, 8 ),
	
	// --------------------
	// begin from http://impactjs.com/forums/code/box2d-plugin
	// In your entity class
	createBody: function() {        
	    var bodyDef = new b2.BodyDef();
	    bodyDef.position.Set(
		(this.pos.x + this.size.x / 2) * b2.SCALE,
		(this.pos.y + this.size.y / 2) * b2.SCALE
	    );
		
	    this.body = ig.world.CreateBody(bodyDef);
	
	    // These two lines define the shape
	    // e.g. b2.PolygonDef, b2.CircleDef
	    var shapeDef = new b2.CircleDef();
	    shapeDef.radius = 8 * b2.SCALE;
		
	    shapeDef.density = 1;
	    this.body.CreateShape(shapeDef);
	    this.body.SetMassFromShapes();    
	},
	// end from http://impactjs.com/forums/code/box2d-plugin
	// ------------------------
	
	// orginal code for crate entity
	//-------------------------
	// createBody: function() {        
	//	var def = new b2.BodyDef();
	//	def.type = b2Body.b2_dynamicBody;
	//	def.position.Set(
	//		(this.pos.x + this.size.x / 2) * b2.SCALE,
	//		(this.pos.y + this.size.y / 2) * b2.SCALE
	//	);
	//	this.body = ig.world.CreateBody(def);
	//	var shape = new b2.PolygonShape();
	//	shape.SetAsBox(
	//		this.size.x / 2 * b2.SCALE,
	//		this.size.y / 2 * b2.SCALE
	//	);
	//	var fixtureDef = new b2.FixtureDef();
	//	fixtureDef.shape = shape;
	//	fixtureDef.density = 1;
	//	this.body.CreateFixture(fixtureDef);
	//},

	init: function( x, y, settings ) {
		this.addAnim( 'idle', 1, [0] );
		this.parent( x, y, settings );
	}
});


});

Thanks if you take a lot at it. Any thoughts are appreciated.

1 decade ago by quidmonkey

You only need plugins/box2d - not dbox2d (unsure of what that is). What sort of errors is the console giving you?

1 decade ago by pm99

Hi quidmonkey,
dbox2d was a default folder in impactjs. I should mention that I'm currently using the appMobi impactjs game pro pack (not sure if that makes a difference, but I understand it's the same impactjs engine if you purchase impactjs directly from Dom.

Anywho... here's my error log.

GAINIT
XDK_common.js:80Logging: XDKStart
:58888/_appMobi/appmobi.js:1872RemoteBridge2
:58888/?CMD=EMULATOR&TYPE=GAME&PATH=demo.directcanvas/3.4.0/index.html:168index.js URL:http://localhost:58888/demo.directcanvas/3.4.0/index.html
XDK_common.js:80
Logging: SwitchApp
appmobi.js:1872
RemoteBridge2
Resource interpreted as Other but transferred with MIME type undefined.
:58888/?CMD=EMULATOR&TYPE=GAME&PATH=iloop.debun2/3.4.0/index.html:168
index.js URL:http://localhost:58888/iloop.debun2/3.4.0/index.html
lib.js:142


Uncaught TypeError: Cannot read property 'y' of undefined
b2.BroadPhase.__constructorlib.js:142
b2.BroadPhaselib.js:141
b2.World.__constructorlib.js:351
b2.Worldlib.js:349
ig.Box2DGame.ig.Game.extend.createWorldFromMapgame.js:42
ig.Box2DGame.ig.Game.extend.loadLevelgame.js:24
window.ig.Class.extend.prototype.(anonymous function)impact.js:394
ig.Box2DGame.extend.loadLevelmain.js:48
window.ig.Class.extend.prototype.(anonymous function)impact.js:394
ig.Box2DGame.extend.initmain.js:35
Classimpact.js:423
ig.System.ig.Class.extend.setGameNowsystem.js:63
ig.System.ig.Class.extend.setGamesystem.js:57
ig.Loader.ig.Class.extend.endloader.js:60
ig.Loader.inject.endloader.js:27
proto.(anonymous function)impact.js:365
(anonymous function)

Sincerely,
PM99

1 decade ago by korzen303

Hi, how can I use ig.world.Raycast(callback, pointA, pointB) function?

I've got it running on a server side in Java, but I am not sure how to create callback function in JS. So far I've tried:
ig.world.RayCast(
 function(fixture, point, normal, fraction )
 { 
  this.infoText = "Frac: " +fraction;
  return fraction;
 }, 
 startVec, 
 endVec) );

and

var clbbck =  function(fixture, point, normal, fraction )
 { 
  this.infoText = "Frac: " +fraction;
  return fraction;
 };

ig.world.RayCast(clbbck, startVec, endVec);

but without any luck. The callback is not invoked at all.

Cheers

1 decade ago by pm99

Hi
@Dominic, @Arantor, @Quidmonkey
I finally got what I believe are my balls! (ok that sounded bad). I say 'believe' because I can't actually see them yet, but I can tell a 'round' entity exists where I placed it.

I was perusing the appmobi tutorials and saw a brief description on the difference between impactjs standalone and impactjs via appmobi (If I've stated that correctly).

There was pointed out a couple of key differences (and I suppose I really should've been in the appmobi forums). They are:

1. the plugin folder has a dbox2d folder vs impact's 'box2d' folder, so require the former not the latter for appmobi folks. (as quidmonkey caught and mentioned)
2. radius must be set via SetRadius() instead of .radius
(there are more differences, but these were the ones i immediately required to get to work).
3. The balls are not visible though. Any thoughts why I can't them? I'm going to try Dominic's debug code above to see those sphere outlines, but in the end, I should see at a minimum the crate rolling inside the ball... no? (since my animsheet points to the crate for now... i suspect it's an exact pixel matching thing).

Here's the ball entity:
EntityBall = ig.Box2DEntity.extend({
	size: {x: 16, y: 16},
	
	type: ig.Entity.TYPE.B,
	checkAgainst: ig.Entity.TYPE.NONE,
	// Collision is already handled by Box2D!
	collides: ig.Entity.COLLIDES.NEVER,
	
	animSheet: new ig.AnimationSheet( 'media/crate.png', 16, 16 ),
	

createBody: function() { 
		
		var def = new b2.BodyDef();
		def.type = b2Body.b2_dynamicBody;
		def.position.Set(
			(this.pos.x + this.size.x / 2) * b2.SCALE,
			(this.pos.y + this.size.y / 2) * b2.SCALE
		);
		this.body = ig.world.CreateBody(def);
		
		var shape = new b2.CircleShape();
		shape.SetRadius(7 * b2.SCALE);
		//this.body = ig.world.CreateCircle(shape); i don't know what to do here
		
		var fixtureDef = new b2.FixtureDef();
		fixtureDef.shape = shape;
		fixtureDef.friction = 5;
		fixtureDef.density = 1;
		fixtureDef.restitution = .25;
		current = this;
		this.body.CreateFixture(fixtureDef);
		
	}

1 decade ago by quidmonkey

The balls are visible because of the debug. The debug draws the shape or "hitbox" of the Entity.

1 decade ago by pm99

Thanks @quidmonkey,
I forgot to add the init function at the end. Now I see my balls! YA! So happy. : )

Thanks for your reply though. Much appreciated!

code added:
init: function( x, y, settings ) {
		this.addAnim( 'idle', 1, [0] );
		this.parent( x, y, settings );
	}

1 decade ago by obj63

Hi Everyone, Thanks for the steps on how to create a round object it is working perfect. The only thing I am not sure how to setup though is to display the outer stroke when not in debug mode. Either that or a way to fill the circle with a tiled image or solid color?

Any one know how to set this?
TIA,
Joe
Page 1 of 2
« first « previous next › last »