Box2D

Monkey Forums/Monkey Programming/Box2D

hardcoal(Posted 2011) [#1]
Can any one post a full code
that give an example of a box2d use.

the main demo doesnt let you check a single demo by it self.
so i cant learn anything from it.

just a simple box creation will do.

tnx


hardcoal(Posted 2011) [#2]
tnx for all the help it really helped

with all the demos you have i dont even see one single demo
that has FunctionMain and all the render process.

so how can you learn like that..


Volker(Posted 2011) [#3]
Hi hardcoal,

just yesterday I posted a box2d screen for using
box2d with Diddy in the code section :-).
It should cover a lot of things like initializing, creating bodies,
collision detection:
http://www.monkeycoder.co.nz/Community/posts.php?topic=1764


hardcoal(Posted 2011) [#4]
Thats good news . ILL go check it out . See what i can do
thanks


hardcoal(Posted 2011) [#5]
I also dont understand what is the diffrence betwin Diddy / Fling and using directly box2d module.
I didnt get into deep each one of this modules
but what is going on? what are all this seperate module for.
which one should I use...

now im concentrating on directly using box2d. trying to figure out what is going on on there.

i had an easy life understanding physx engine, JVODE and Newton engine.
but not easy time yet understanding how to use box2d under monkey.

so far i was too busy working on my Element manager engine which im very pleased of.
this manager ive made is going to make game creating i walk in a park for me.
so it was worth working on it for the past months.
soon after ill figure out box2d use i will put some demo of my
Element manager creations


hardcoal(Posted 2011) [#6]
Volker. why does everything falls so slow.
ive changed the update rate and still didnt show a diffrence


therevills(Posted 2011) [#7]
hardcoal... what makes things fall? Then look in the code ;)


hardcoal(Posted 2011) [#8]
hmmm I dunno Sex? maybe god?

i guess from your answer that the objects are probably very big.


therevills(Posted 2011) [#9]
I give up!


hardcoal(Posted 2011) [#10]
I dont


Volker(Posted 2011) [#11]
Einstein: Increase the property of space-time geometry.
Newton: Increase the force which physical bodies attract proportional to their mass.
Volker: Use SetGravity()


hardcoal(Posted 2011) [#12]
LoL tnx I figured this out that wasnt the issue.
I thought theres another way beside increasing gravity.

Cheers


Volker(Posted 2011) [#13]
For box2d you should really use some scaling.
In my example an object with 50 pixels behaves like a 50 meter object
(1 pixel = 1 meter).
So create small objects and scale the drawings.
I didn't implement it to keep things easy.


Neuro(Posted 2011) [#14]
I think instead of some sample code or tech demo with everything thrown together, he's looking for an actual example of a project using Box2d along with explanation of how to get it working with sprite objects, and how to manipulate it.


hardcoal(Posted 2011) [#15]
true neuro.

ive being braking my mind all this Saturday eliminating
code lines from the samples
trying to make it work in the most basic way possible.
yet no success... :(

I know i have lake of knowledge in all aspects.
i didn’t come with blitzmax history i came with blitz3d.
nor any other advances language knowledge like c++ or java.
makes it triple harder..

so by elimination process im trying to get to the core

its exactly what you said neuro. a simple demo that explains each line
would have saved allot of time for many people.


hardcoal(Posted 2011) [#16]
here is my last experiment.
i mixed fling and diddy since i dont know exactly what does what.
im trying to make a simple cube appears on air and falls down thats it.

i know its a big mess but thats where im standing.
i want to get to the most minimized code you need in order to get a physical engine work


'fling
Import mojo
Import fling.allfling
Import fling.col.allcol

'Diddy
Import diddy
Import box2d.collision
Import box2d.collision.shapes
Import box2d.common.math
Import box2d.dynamics.contacts
Import box2d.dynamics
Import box2d.flash.flashtypes
Import box2d.common.math.b2vec2

Function Main()
New MainRender
End Function

Class MainRender Extends App

Field BXworld : b2World
Field contactlistener : ContactListener
Field m_velocityIterations : int = 10
Field m_positionIterations : int = 10
Field m_timeStep:Float = 1.0/60
Field m_physScale:Float = 1' 30
Field m_debugdrawscale :Float=1

Method OnCreate()
SetUpdateRate(60)
BXworld = new b2World
BXworld.SetGravity(0.9,0.9)
End Method

Method OnUpdate()
If( MouseHit( MOUSE_LEFT) )
FireBlock( MouseX(), MouseY())
End
BXworld.Update(0,1)
End Method

Field MojDrawer : MojoDraw = new MojoDraw()

Method OnRender()
Cls 0,0,0
MojDrawer.DrawWorld(BXworld)
End Method

'-------test stuff-----------------------'

Method FireBlock( mouseX : Float, mouseY : Float )

Local pos := new Vector(DeviceWidth(),DeviceHeight())
pos.x += 100
pos.y /= 3
Local v := new Vector( mouseX - pos.x, mouseY - pos.y )
Local k := 15 / v.Length()
v.x *= k
v.y *= k
Local b := new Body(0,0)
b.Set(pos,0,v,2)
b.AddShape( Shape.MakeBox(20,20) )
BXworld.CreateBody(10,10,10,10)
BXworld.AddBody(b)
End


End Class


therevills(Posted 2011) [#17]
Fling = http://tinyurl.com/44nw484
Diddy = http://tinyurl.com/3gp5v4r


muddy_shoes(Posted 2011) [#18]
I've read this thread three or four times now trying to work out what the problem is and I'm honestly stumped. I'm also quite irritated at the sense of entitlement being expressed.

"a simple demo that explains each line would have saved allot of time for many people."

Firstly, the demos are simple and they are commented. The main demo file is all of 200 lines long and does little else other than set up an array of the individual demos and allow swapping between them. The base test class is a massive 250 lines long, half of which is the file header and mouse handling code that you can freely ignore. The specific test files themselves are nothing but the bare-bones set-up required for that test. What exactly is so brain-bending about looking at these files to see how stuff is set up, I have no idea.

Secondly, as far as "saving a lot of time for other people" are you under the impression that I found the box2d module left on my doorstep or something? The conversion represents weeks of effort. I put that effort in without expectation of thanks or payment but certainly didn't imagine that someone would have the gall to accuse me of wasting their time for releasing it just because they're not finding it easy to use.

Frankly it is what it is and I'm quite happy that there's enough there for anyone to pick it up and use it. If you don't like the demos provided then there are box2d tutorials and books and forums out there to be googled. If all that seems like a waste of your time then it's a mystery to me how you expect to get anywhere. I'm certainly not about to spend more of my energy trying to help you out based on what's written here.


hardcoal(Posted 2011) [#19]
muddy

I dont understand why you think i have complaints towords you and your effort?
secondly I dont expect any ones help if they dont feel right with that.

ye im a guy who complains alot and expect alot.

yes you did a great job!!

I will keep complaining where i see right.
but nothing is towords people who contributed for free!

it is your personal choice if you choose to be offended from
something that you think was directed towords you!

besides, do as you please i dont care


therevills(Posted 2011) [#20]
harcoal, I gave you the biggest clue on how to increase the falling speed and your reply was just stupid.

Your attitude on the forum comes across really bad - try to word your post better and think about the code you are trying to do. The above code you posted makes no sense what so ever.


Dabz(Posted 2011) [#21]
Little guide to gravity:-

Gravity was discovered by Sir Isaac Newton. It is chiefly noticeable in the autumn, when the apples are falling off the trees.

Dabz


hardcoal(Posted 2011) [#22]
therevills

you gave me a clue?
it was more like making lough of me so what you expect that i will say
"ohhh the gravity thing that newton discovered..."

I told you guys
monkey was made for blitzmax expirianced users
nothing is written before you buy monkey or on the website (that ive noticed) that you should
have an extend programming expiriance before touching it.

you are all here as i noticed come from blitzmax background
thats why its sooo easy for you.

and i get all the angre just for breaking my head
with very bad tutorials made mainly for expirianced guys..

I started monkey without even knowing what function main is..
what is class..
and more mystries....

yea there are explantions about class and function main
on the tutorial but its hard to know what/where to start.

I will make a descent website for monkey in the future
(FOR BEGGINERS!!)
that all newbies will be directed there.

the only thing that stops me is a good website editor
and didnt find one that suites me well.

for the last time!
you dont have to like me
you dont have to help me
i will write my quastions and anyone can feel free to ignore me.

i dont attack anyone, im the one who is being attacked


Dabz(Posted 2011) [#23]
The biggest thing hardcoal is that one of the most important things about getting help is to take any advice onboard, be it a little hint, to a full blown piece of source code.

You don't get it, then fair do's, I was like that once too, a bit green behind the lug holes, I'd ask questions, like yourself, and I'd get answers... Nine times out of ten it wouldnt be a well commented piece of code written in the language I was using, nope, it would be tit bits, or an article written for some other programming language which I had to decipher, thats the deal!

Currently, it seems your not entirely clued up on the basics of monkey, which begs the question, why on earth are you trying to use a 3rd party module that will ultimately add more confusion to the equation?

Here's some advice, for the minute, forget Box2D... Play with what comes with Monkey, read the docs, explore the code contained in the samples and module folders... Try and make a little game such as tic-tac-toe, or a small shooter.

Just settle down and settle in, you'll get there, but for your benefit, realize it takes a bit more work then just hammering forums and expecting answers which are 100% what your after... Its not going to happen!

Dabz


hardcoal(Posted 2011) [#24]
Sure, Dabz. Now that I realized the source of the problem which
is that im trying to learn 2,3 things at once.

not knowing which is monkey related command or which is a specific module command.
makes it very hard..

I am an advanced programmer so I dont need to go threw making Tic tak games.

Ive allready made some big projects that are soon to be proven and realsed

I wont giveup on box2d thats for sure. ill just keep on figuring out stuff my self

Cheers


Dabz(Posted 2011) [#25]

I am an advanced programmer so I dont need to go threw making Tic tak games.



I'm like to think I'm okay at programming, but every single language I've tried over the years, I've built a simple game to begin with... Its not demeaning, its just a good exercise... My first app was this in monkey:-

http://www.denathorn-games.net/croco/croco.html

Just a bit of simple array checking, nothing more really... I learnt heaps building that, and as such, pretty comfy with what monkey is about, so, moved on to a bigger and better project.

In my opinion, being an advanced programmer means jack poop, I've been programming since I was nine years old and I get stuck sometimes, there's always something to learn, there's always basics of something or other to pickup,

And its always the same, when using something new, don't run before you can walk... Makes life a lot easier!

Dabz


hardcoal(Posted 2011) [#26]
Sure.
I agree with your approch.
I did start by making an image move on the screen and other simple tasks.

There will be always new things to learn thats for sure.

Advanced programmer means Im not a begginer nor a Pro.
and im still in the walking faze Dabz

Cute Game you made. good remake


muddy_shoes(Posted 2011) [#27]
you are all here as i noticed come from blitzmax background
thats why its sooo easy for you.


This isn't true. I have no experience with BlitzMax or any other Blitz product apart from a few experiments on the Amiga. I actually find Monkey's syntax quite unintuitive.

i dont attack anyone, im the one who is being attacked


So when you state that other people are producing "bad tutorials" or make little passive-aggressive snipes at the help or feedback you are offered it's not an attack, but when others say anything about you it is? How convenient for your world-view.

It's a rainy Saturday morning and I don't fancy going for a walk, so forgive me for going against what I said above and trying to offer some help to you. Specifically some help about getting help with programming questions.

Your first post in this thread was clearly passed by. Why do you think that is? If you look elsewhere on the forum you'll see questions being answered, even questions about Box2D, so what's different about your question? Allow me to break down how I feel when reading it:

Can any one post a full code that give an example of a box2d use.


The box2d demo is a "full code" by any reasonable definition. Given that, I've no idea what is being asked for. Besides this, I generally raise my eyebrows at blunt requests for others to put in non-trivial effort creating tutorials or examples with absolutely zero effort put into the request.

the main demo doesnt let you check a single demo by it self.


This just makes no sense. The demos are structured to split out the individual set-up code explicitly so that you _can_ look at each one in isolation. Anyone declaring that they can't fathom the two base files for the demos is having trouble understanding Monkey, not box2d.

so i cant learn anything from it.


Reading "i cant learn anything from it" as a response to a piece of code that I know very well is suited to learning from raises a warning flag. It suggests that when the poster can't immediately understand something they come to the conclusion that there's something wrong with what they're trying to understand. Trying to teach such people anything is not very productive or much fun.

If you want help then you need to be able to help people to help you. You can't expect to fire off a half-coherent post in thirty seconds that will result in someone else spending an hour or more crafting a detailed answer for you. You might be lucky enough that someone already has a suitable bit of code to post, but mostly not.

These four points might be of use:

1. Ask specific questions rather than making broad requests.
2. Explain/show what effort you've put into finding the answer yourself. This demonstrates that you're at least trying and saves people telling you stuff that you already know.
3. If you've got code, post it. If you're posting code then provide an explanation of the problems you're having. The code you posted above won't even compile so what is anyone meant to say about it? Also, use the codebox tag and indent the code sensibly.
4. Refrain from biting the hand that feeds.


therevills(Posted 2011) [#28]
therevills

you gave me a clue?
it was more like making lough of me so what you expect that i will say
"ohhh the gravity thing that newton discovered..."



I wasnt making it tough on you... I was trying to make you help yourself.

You asked: "why does everything falls so slow"
I replied: "what makes things fall? Then look in the code"

So the answer is gravity, I then expected you to go have have a look at the source code and find gravity... not exactly hard is it!?

Hardcoal... can I ask how old are you and what country do you come from?


skid(Posted 2011) [#29]
The thing is the answer isn't gravity. Multiply it by 10 or even 100 and things don't fall that much quicker.

If I get around to writing a tutorial I will include my solution to that particular problem.


therevills(Posted 2011) [#30]
In Volker example:

Self.SetGravity(0.0,10) 


All you have to do is alter the "10" to something higher then the objects will fall faster... therefore the answer is gravity.


Samah(Posted 2011) [#31]
The thing is the answer isn't gravity. Multiply it by 10 or even 100 and things don't fall that much quicker.

But they can! After all, F = (G m1 m2) / r^2
http://www.ajdesigner.com/phpgravity/newtons_law_gravity_equation_force.php


muddy_shoes(Posted 2011) [#32]
The thing is the answer isn't gravity. Multiply it by 10 or even 100 and things don't fall that much quicker.


If you're using a fixed physics step (and that's the recommended method) then the visual rate of movement will be dependent on your update mechanism. If you set the physics rate to 1/60th of a second but the app rate doesn't get up to that rate then your simulation will be playing in slow-motion. There are obviously further issues depending on whether you lock the update to the frame or not.


hardcoal(Posted 2011) [#33]
therevills

you really cant make out a profile from someone knowing his age and place of his living. (age maybe...abit)

I told you before i have short fuse thats true, but thats because im suffering from strange sensitivity sitting near current screen technology.
It somehow make me very edgy(no joke)

My english isnt perfect enough to express technical stuffs accuratly.
I thought we are over this as ive said i will figure it on my own no probs.

No complaints to anyone..
No demands...

Hard.c


Volker(Posted 2011) [#34]
The thing is the answer isn't gravity. Multiply it by 10 or even 100 and things don't fall that much quicker.
If I get around to writing a tutorial I will include my solution to that particular problem.


What's your kind of solution skid?
I've added an acceleration controller to my demo in the code section,
which should do the trick.


hardcoal(Posted 2011) [#35]
its exactly what im facing right now.
I think there is an acceleration limit.
no matter what gravity value you will put it will reach a certain speed
and stop accelerating.
there should be some parameter that sets the limit and im looking for it too.


hardcoal(Posted 2011) [#36]
After A Long Hard Work A Little Demo Of Box2D. (what I was looking all along)
for the begginers among us

'A Simplfield Demo Assamabled from Other Demos Thanks to Volker and muddy_shoes and my own style as well.

'Shows In Real Basic Way how Box2D Engine works.
'Any one who see a place for corrections in the code and new Remarks
'Is free to do it and republish. All in good of helping the new guys around here.
'If you find this demo usufale I will be glad to know and will be encorouged to make more demos of that sort for begginers among this community (Like me)


'----Includes----'
Import box2d.collision
Import box2d.collision.shapes
Import box2d.common.math
Import box2d.dynamics.contacts
Import box2d.dynamics
Import box2d.flash.flashtypes
Import box2d.common.math.b2vec2

'----Test Zone----'
Function Main()
	New Box2DLoop	
End Function

'----Main Loop----'
Class Box2DLoop Extends App

	'Box 2D Parameters Set
	Field BXworld				: b2World					'Box2D physical World Object
	Field m_velocityIterations	: int 	= 10				'Dont know whats this yet.
    Field m_positionIterations	: int 	= 10				'Either that.
    Field m_timeStep			: Float = 1.0/60			'Hmm, I know whats this but no changes accured when presetting.
    Field m_physScale			: Float = 1 ' 30       		'I Change its value but same results.
	Field m_debugdrawscale		: Float	= 10	 			'This Affects the size of the physical Body Display
			
	Field b:b2Body 			      'A phsyical body Type of box2d decleration.
	
	
	'--Main Methods----'
	
	Method OnCreate()
	
		'Box2D Setups
		Local doSleep:Bool = True		
			  
		'Creating a new Box2D World
		 BXworld = New b2World(New b2Vec2(0,0),doSleep)	
		 SetGravity(0.0,9.7) 
		
		'Creating a Ground Box
		'From some reason, if you dont create this ground box nothing works...
		b=self.CreateBox(0,40,70,2)
		b.SetUserData(New StringObject("ground")) 'give object a name for collision detection in contactlistener
		
		'Display Setup
		SetUpdateRate(60)
		
		'Box2D Debug Settings   		'Delete this section if you dont need to see the physical process in graphics.
		Local dbgDraw :b2DebugDraw = New b2DebugDraw()       
	          dbgDraw.SetDrawScale(m_debugdrawscale) 
		      dbgDraw.SetFillAlpha(0.3)
		      dbgDraw.SetLineThickness(1.0)
		      dbgDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit)'| b2DebugDraw.e_pairBit)
		      BXworld.SetDebugDraw(dbgDraw)
		
	End Method
	
	Method OnRender()
		Cls		
		
		'Box2D Display Section
		 BXworld.DrawDebugData() 'Delete this line if you dont need to see the physical process in graphics. (must also delete 'Box2D Debug Settings section above)
				 
		 '(Mojo commands must come only after the Box2D Debug Draw or it wont be seeing)
		 
		 'Mojo Display Section
		  SetColor 255,255,255
		  DrawText 	"Obj X Position: "+b.GetPosition.x*10,5,425
		  DrawText 	"Obj Y Position: "+b.GetPosition.y*10,5,440 
		  
		  DrawText "Press Mouse Button to create a new Sphere",5,458
		  
	End Method
	
	Method OnUpdate()
					
		'The Stepping of Box2D Engine
		BXworld.TimeStep(m_timeStep,m_velocityIterations,m_positionIterations)
		BXworld.ClearForces()	'Dont know why you need this..	
				
		'Add a new Sphere
		If( MouseHit( MOUSE_LEFT) ) 						
			b=Self.CreateSphere(MouseX()/10,MouseY()/10,4)	'Creates a new Physical Sphere.
			b.SetUserData(New StringObject("sphere"))		'Dont know what this for.
			
			Print "A New Sphere Created"
		End
	End Method
	
	'------------Create Sphere,Box And Set Gravity Functions-----------------------------'
	
	Method CreateSphere:b2Body (xpos:Float,ypos:Float,radius:Float,static:Bool=false)	'Creates a Physical Sphere
		Local fd :b2FixtureDef = New b2FixtureDef()
		Local bd :b2BodyDef = New b2BodyDef()
		Local cd :b2CircleShape = New b2CircleShape()	  
		'		
		cd.m_radius  = radius
		fd.density = 2
		fd.restitution = 0.2
		fd.friction = 0.5
		fd.shape=cd
		if static=true
			bd.type = b2Body.b2_staticBody ' a static body
		else
			bd.type = b2Body.b2_Body 'a dynamic body
		endif
		bd.position.Set(xpos,ypos)
		Local b :b2Body
		b = self.BXworld.CreateBody(bd)
		b=Self.BXworld.CreateBody(bd)
		b.CreateFixture(fd) 			
		Return b	
	End Method
	
	Method CreateBox:b2Body (xpos:Float,ypos:Float,width:Float,height:Float,static:Bool=true)	'Creates a Physical Box
		Local fd :b2FixtureDef = New b2FixtureDef()
		Local sd :b2PolygonShape = New b2PolygonShape()
		Local bd :b2BodyDef = New b2BodyDef()
		if static=true
			bd.type = b2Body.b2_staticBody
		else
			bd.type = b2Body.b2_Body
		endif		
		fd.density = 1.0 
		fd.friction = 0.5
		fd.restitution = 0.1
		fd.shape = sd
		sd.SetAsBox(width,height)
		bd.position.Set(xpos,ypos)
		Local b :b2Body
		b = self.BXworld.CreateBody(bd)		
		b.CreateFixture(fd)	
		'
		Return b	
	End Method
	
	Method SetGravity:Void(x:Float,y:Float)	'An easier Method to setup gravity
		Self.BXworld.SetGravity(New b2Vec2(x,y))
	End Method
	
End Class



hardcoal(Posted 2011) [#37]
OMG. I just realized I waisted two Three days on a problem
that was stupid
because I used another Coder code with out really checking it.

The Code was fine. I just didnt spend time to check it well.

Gees..


TheRedFox(Posted 2011) [#38]
Good for you!

Hey, having Box2D in Monkey is a godsend.


hardcoal(Posted 2011) [#39]
Its essential


Rob Pearmain(Posted 2011) [#40]
This demo is excellent, I too needed a beginners guide.

All the examples I have seen so far use debug data.

To draw an image for each of the objects, is there a list of objects that can be enumerated, can you get their angle and draw an image in place accordingly, is there a simple example somewhere?


Volker(Posted 2011) [#41]
Store a reference of the created body in your Gameobject or whatever you call it.
Then do something like this:
Local rotation:Float=RadToDeg(body.GetAngle())*-1
DrawImage(yourimage,body.x,body.y,rotation,1,1)

Function RadToDeg:Int(rad:Float)
  ' converts radian to degrees. Box2D uses radians, Monkey degrees.
  Return rad*180/PI
End Function



Rob Pearmain(Posted 2011) [#42]
Awesome, many thanks


hardcoal(Posted 2011) [#43]
thanks. if ill have time ill release an example with image relations to box2d coords


Dabz(Posted 2011) [#44]
I bet you probably learnt more doing that then if you were given the code on a plate! ;)

Dabz


hardcoal(Posted 2011) [#45]
lol true i agree


Rob Pearmain(Posted 2011) [#46]
A conversion of Todds box2dFlash tutorial 1 upgraded to 2.1a


'----Includes----'
Import box2d.dynamics.b2world

'----Test Zone----'
Function Main()
	New Box2DLoop()
End Function

'----Main Loop----'
Class Box2DLoop Extends App

	Field _world:b2World

	Field RATIO:Float = 8
	
	Field _nextCrateIn:Int
	
	
	
	'--Main Methods----'
	
	Method OnCreate()
	
		' 1. Set Up World
		setupWorld()
		' Create Walls and Floors
		createWallsAndFloor()
		setupDebugDraw()
		_nextCrateIn = 0
		
	
		'Display Setup
		SetUpdateRate(60)
		

			  
	End Method
	
	Method setupDebugDraw:Void()
	
	
	    
			'Box2D Debug Settings   		'Delete this section if you dont need to see the physical process in graphics.
		Local dbgDraw :b2DebugDraw = New b2DebugDraw()       
	    
        dbgDraw.SetDrawScale(10.0)
        dbgDraw.SetFillAlpha(0.3)
        dbgDraw.SetLineThickness(1.0)
        dbgDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit)'| b2DebugDraw.e_pairBit)
        _world.SetDebugDraw(dbgDraw)
		
	End
	Method OnRender()
		Cls		
		
		_world.DrawDebugData()
		  
	
		
	End Method
	
	Method OnUpdate()
					
		_world.TimeStep(1.0 /30,10,10)
		_world.ClearForces()
		
		_nextCrateIn = _nextCrateIn - 1
		
		if _nextCrateIn  <=0 And _world.m_bodyCount < 80 Then
			addARandomCrate()
			_nextCrateIn = 10
		EndIf
		
	End Method
	
	
	Method setupWorld()
	
		
		
		' Define gravity
		Local gravity:b2Vec2 = new b2Vec2(0,9.8)
		
		' Ignore Sleeping Objects
		Local ignoresleeping:Bool = true
		
		_world = New b2World(gravity,ignoresleeping)

		
		
		
	End
	
	Method addARandomCrate()
		Local fd:b2FixtureDef = new b2FixtureDef()
		Local sd:b2PolygonShape = new b2PolygonShape()
		Local bd:b2BodyDef = new b2BodyDef();
		bd.type = b2Body.b2_Body
		
		fd.friction = 0.8
		fd.restitution = 0.3
		fd.density = 0.7
		fd.shape = sd
		
		sd.SetAsBox(randomInt(5,40) / RATIO, randomInt(5, 40) / RATIO)
		
		bd.position.Set(randomInt(15,530) / RATIO, randomInt(-100, -10) / RATIO)
		bd.angle = randomInt(0,360) * 3.14 / 180
		
		Local b:b2Body = _world.CreateBody(bd)
		b.CreateFixture(fd)
	
	End
	
	Method randomInt:Int(lowVal:Int, highVal:Int)
		
		if (lowVal <= highVal)
			
			Return lowVal + Floor(Rnd() * (highVal - lowVal + 1))
			
		EndIf
	End
	
	Method createWallsAndFloor:Void()
		
		Local sd:b2PolygonShape = new b2PolygonShape()
		Local fd:b2FixtureDef = new b2FixtureDef()
		Local bd:b2BodyDef = new b2BodyDef()
		bd.type = b2Body.b2_staticBody
		
		sd.SetAsArray([New b2Vec2(0,0),New b2Vec2(550/RATIO,0), New b2Vec2(550/RATIO,10/RATIO), New b2Vec2(0,10/RATIO)])
			
	
		fd.friction = 0.5
		fd.restitution = 0.3
		fd.density = 0.0
		fd.shape = sd
		
		bd.position.Set(0,560/RATIO)
		
		Local b:b2Body = _world.CreateBody(bd)
		b.CreateFixture(fd)
		
		Local sdwall:b2PolygonShape = new b2PolygonShape()
		Local fdwall:b2FixtureDef = new b2FixtureDef()
		Local bdwall:b2BodyDef = new b2BodyDef()		
		bd.type = b2Body.b2_staticBody
		
		fdwall.friction =  0.5
		fdwall.restitution = 0.3
		fdwall.density = 0
		fdwall.shape = sdwall
		sdwall.SetAsBox(5/RATIO,390/RATIO)
		
		bdwall.position.Set(5/RATIO,195/RATIO)
		
		Local leftwall:b2Body = _world.CreateBody(bdwall)
		leftwall.CreateFixture(fdwall)
		
		bdwall.position.Set(545/RATIO,195/RATIO)
		
		Local rightwall:b2Body = _world.CreateBody(bdwall)
		rightwall.CreateFixture(fdwall)

		
		
	End
End Class



Amon(Posted 2011) [#47]
Thanks for the little code snippet, hardcoal. I knew nothing of Box2D or had even attempted to use it but from what you posted it seems fun to dabble around with all this physics stuff.

I seem to see a little bit of a militant in you Mr hardcoal. What I'll say to you is this though; inside us all there is a hungry Troll called anger. This hungry Troll called anger has one sole purpose and that is it wants to eat all the resources of thought energy you have in your mind. Not just immediate creative energy but the reserves, the backups, the generators that create more beautiful energy to power the imagination...the lot basically.

What does that mean, I think you may be saying?

It means if you feed this hungry Troll called anger whenever it rears its angry head the only outcome will be that it consumes your entire mind to the point where creativity, happiness, well being, concentration, logic, have all be starved of energy and all that is left is just one big angry Troll called anger.

Is what I have said just a bunch of rubbish? I'll leave that to you and especially to the rest of you guys who actually believe in Gravity.

After all, nothing exists that is solid as Mass is one giant illusion. Find me the Higgs Bosson...you can't can you. Don't tell me about standard models this and that because I'll listen, but all I'll hear is Blah blah blah :)

Don't try to feed me evolution either.

:D


hardcoal(Posted 2011) [#48]
yeap Amon, all true.. without getting into details. :)


hardcoal(Posted 2011) [#49]
Besides that..

I want to add more demos and stuff. for others issues..
but you know... too busy taking care of my cat... and stuff


slenkar(Posted 2011) [#50]
inside us all there is a hungry Troll called anger. This hungry Troll called anger has one sole purpose and that is it wants to eat all the resources of thought energy you have in your mind.


Thats what its like being a taurus I spose.
(famous for their anger once aroused, but its difficult to arouse)


Dabz(Posted 2011) [#51]
I'm a taurus, May 11th! \o/



Dabz


slenkar(Posted 2011) [#52]
uh-oh
You're supposed to be about momentum, hard to get going, but then hard to stop when are going.(applies to work, emotions etc.)


Dabz(Posted 2011) [#53]
lol, sounds about right nowadays! :D

Dabz


CodeGit(Posted 2011) [#54]
I know this is off subject but I found what Amon is saying very interesting.

Here is a quote from Nelson Mandela - “Resentment is like drinking poison and then hoping it will kill your enemies.”


hardcoal(Posted 2011) [#55]
thumbs up for amon


hardcoal(Posted 2011) [#56]
I must admit this damn box2d really gives me a hard time.
yea i know its a great physics engine.
but the logic of it is all meant to be confusing in any way the author
found right.

you need to spend ages to understand it and its only a 2d physics engine
not a 3d...

eventually i will get over it cause i have no choice..
and i will put clear demos.. of how to make stuff.

atm I’m still wasting hours trying to figure it out.

since im not using flash i cant checkout demos, I only have monkey.

no one need to relate to this post, i just take out a little frustration out of my system.


hardcoal(Posted 2011) [#57]
found a nice and clear box2d tutorial video just a moment ago.

worth taking a look

http://www.kerp.net/box2d/displaylesson.php?chapter=1&lesson=5

its for flash but still .. can reflect from

Another nice thing
--------------------

http://www.brainblitz.org/BoxCAD/

I just realized that it also produce a code. great thing


hardcoal(Posted 2011) [#58]
Ive added a new demo for Joints.
Its being hard time understanding this engine
it would be nice if more people make simple demos along with explanations
people who allready knows this engine well.

Demo 1 is again creating a basic box



Demo 2 Creating a Joint.



I still know almost nothing about setting a joint
but im working on it.


hardcoal(Posted 2011) [#59]
when are we going to see chipmunk module ready
so i can get reed of this head ache called box2d?

i wish soon


bruZard(Posted 2011) [#60]
yet another Box2D example ;)



Strict

Import mojo
Import box2d.common
Import box2d.collision
Import box2d.dynamics

Function RadToDeg:Int(rad:Float)
	if rad <> 0.0 Then Return (rad * 180.0) / PI Else Return 0
End Function

Class CEntity
	Field bodyDef:b2BodyDef
	Field bodyShape:b2PolygonShape
	Field body:b2Body
	Field fixtureDef:b2FixtureDef
	Field img:Image
	
	Method CreateBox:Void(world:b2World, x:Float, y:Float, width:Float, height:Float, static:Bool = False)
		Self.fixtureDef	= New b2FixtureDef()
		Self.bodyShape	= New b2PolygonShape()
		Self.bodyDef	= New b2BodyDef()
		
		If static = True
			Self.bodyDef.type = b2Body.b2_staticBody
		Else
			Self.bodyDef.type = b2Body.b2_Body
		endif		
		
		Self.fixtureDef.density		= 1.0 
		Self.fixtureDef.friction	= 0.3
		Self.fixtureDef.restitution	= 0.1
		Self.fixtureDef.shape		= Self.bodyShape
		Self.bodyDef.position.Set(x, y)
		Self.bodyShape.SetAsBox(width, height)
		Self.body = world.CreateBody(Self.bodyDef)
		Self.body.CreateFixture(Self.fixtureDef)
		Self.bodyDef.allowSleep		= True
		Self.bodyDef.awake			= True
	End
	
	Method CreateImageBox:Void(world:b2World, img:Image, x:Float, y:Float, static:Bool = False)
		Self.img = img
		Self.img.SetHandle(Self.img.Width() / 2, Self.img.Height() / 2)
		Self.CreateBox(world, x, y, img.Width() / 2, img.Height() / 2, static)
	End
	
	Method SetFriction:Void(friction:Float = 0.5)
		Self.fixtureDef.friction = friction
		Self.body.CreateFixture(Self.fixtureDef)
	End
	
	Method SetDensity:Void(density:Float = 1.0)
		Self.fixtureDef.density = density
		Self.body.CreateFixture(Self.fixtureDef)
	End
	
	Method SetRestitution:Void(restitution:Float = 0.1)
		Self.fixtureDef.restitution = restitution
		Self.body.CreateFixture(Self.fixtureDef)
	End
	
	Method SetMass:Void(mass:Float)
		Local md:b2MassData = new b2MassData()
		Self.body.GetMassData(md)
		md.mass = mass
		Self.body.SetMassData(md)
	End
	
	Method SetImage:Void(img:Image)
		Self.img = img
	End
	
	Method Draw:Void(ratio:Float = 1.0)
		if Self.img <> Null
			Local x:Float	= self.body.GetPosition().x
			Local y:Float	= self.body.GetPosition().y
			Local r:Float	= RadToDeg(Self.body.GetAngle()) * -1
			
			DrawImage(Self.img, x, y, r, 1.0, 1.0, 0)
		EndIf
	End
End

Class CWorld
	Field world:b2World
	Field m_velocityIterations:int
    Field m_positionIterations:int
    Field m_timeStep:Float
	Field ratio:Float
	
	Field entities:List<CEntity>
	
	Method New(ratio:Float = 1.0, gravityX:Float = 0.0, gravityY:Float = 10.0)
		Self.ratio = ratio
		Self.world = New b2World(New b2Vec2(gravityX, gravityY), True)	
		Self.world.SetGravity(new b2Vec2(gravityX, gravityY))
		
		Self.m_velocityIterations	= 3
		Self.m_positionIterations	= 3
		Self.m_timeStep				= 1.0 / 10.0
		
		Self.entities = New List<CEntity>()
	End
	
	Method update:Void()
		Self.world.TimeStep(self.m_timeStep, self.m_velocityIterations, self.m_positionIterations)
		Self.world.ClearForces()
	End
	
	Method render:Void()
		if Self.entities.Count() > 0
			For Local e:CEntity = eachin self.entities
				if e <> Null e.Draw(self.ratio)
			Next				
		EndIf
	End
	
	Method CreateBox:CEntity(x:Float, y:Float, width:Float, height:Float, static:Bool = false)
		Local entity:CEntity = new CEntity()
		entity.CreateBox(Self.world, x, y, width, height, static)
		Self.entities.AddLast(entity)
		
		Return entity
	End
	
	Method CreateImageBox:CEntity(img:Image, x:Float, y:Float, static:Bool = False)
		Local entity:CEntity = new CEntity()
		entity.CreateImageBox(Self.world, img, x, y, static)
		Self.entities.AddLast(entity)
		
		Return entity
	End
End

Class CTest extends App
	Field world:CWorld
	Field player:Image
	Field playerEntity:CEntity
	Field groundEntity:CEntity
	Field ratio:Float
	
	Method OnCreate:Int()
		Self.ratio			= 640.0 / DeviceWidth()
		Self.world 			= New CWorld(Self.ratio)
		Self.player			= LoadImage("player.png")
		Self.groundEntity	= Self.world.CreateBox(0, DeviceHeight() - 10, DeviceWidth(), 10, True)
		
		SetUpdateRate(60)
		
		Return 0
	End
	
	Method OnUpdate:Int()
		Self.world.update()
		
		if MouseHit() Or TouchHit()
			Local mx:Float	= MouseX()
			Local my:Float	= MouseY()
			Local e:CEntity = self.world.CreateImageBox(self.player, mx, my)
			e.body.SetAngularVelocity(Rnd(-0.1, 0.1))
			
		EndIf
		Return 0
	End
	
	Method OnRender:Int()
		Cls(90, 120, 200)
		#if TARGET = "android"
			DrawText("touch to spwan a new crate", DeviceWidth() / 2, 20, 0.5)
		#Else
			DrawText("left click to spwan a new crate", DeviceWidth() / 2, 20, 0.5)
		#EndIf
		
		Self.world.render()
		
		Return 0
	End
End

Function Main:Int()
	New CTest()
	Return 0
End


Flash: http://www.sedm.de/monkey/bnb
Android: http://www.sedm.de/monkey/bnb/box2d.apk

[EDIT]
for the android version i've added a qr code to the flash version
[/EDIT]


hardcoal(Posted 2011) [#61]
Thats great bruzard....
can you make a demo with mouse grabing?
or any small demo that explains one principle will be great.


Ads(Posted 2013) [#62]
Apologies for resurrecting a long dead thread, but I've been taking an interest in Box2D again recently for a project I'm planning. bruZards code above works fine; but there's one fundamental aspect of Box2D that needs to be taken into account - it's not 1 unit = 1 pixel.
Assuming a body object is the size of an image will give you the weird slow movement you guys have been experiencing, Box2D is not great working with giant objects. If you scale the body object down it works as intended (in my code below, I've scaled the size of the body object down 64 times, so 1 pixel = 0.015625 units, or 1 unit = 64 pixels).

The two images 'crate.png' & 'crate2.png' can be anything of any size.

Lastly, you need to decrease the timestep otherwise it will run way way too fast; I've changed it from 1/10 to 1/60. :)

Strict

Import mojo
Import box2d.common
Import box2d.collision
Import box2d.dynamics

Function RadToDeg:Int(rad:Float)
	if rad <> 0.0 Then Return (rad * 180.0) / PI Else Return 0
End Function

Class CEntity
	Field bodyDef:b2BodyDef
	Field bodyShape:b2PolygonShape
	Field body:b2Body
	Field fixtureDef:b2FixtureDef
	Field img:Image
	
	Method CreateBox:Void(world:b2World, x:Float, y:Float, width:Float, height:Float, static:Bool = False)
		Self.fixtureDef	= New b2FixtureDef()
		Self.bodyShape	= New b2PolygonShape()
		Self.bodyDef	= New b2BodyDef()
		
		If static = True
			Self.bodyDef.type = b2Body.b2_staticBody
		Else
			Self.bodyDef.type = b2Body.b2_Body
		endif		
		
		
		Self.fixtureDef.density		= 1.0 
		Self.fixtureDef.friction	= 0.9
		Self.fixtureDef.restitution	= 0.3
		Self.fixtureDef.shape		= Self.bodyShape
		Self.bodyDef.position.Set(x, y)
		Self.bodyShape.SetAsBox(width, height)
		Self.body = world.CreateBody(Self.bodyDef)
		Self.body.CreateFixture(Self.fixtureDef)
		Self.bodyDef.allowSleep		= True
		Self.bodyDef.awake			= True
		
	End
	
	Method CreateImageBox:Void(world:b2World, img:Image, x:Float, y:Float, static:Bool = False)
		Self.img = img
		Self.CreateBox(world, x, y, float(img.Width()) / 128.0, float(img.Height()) / 128.0, static)
	End
	
	Method SetFriction:Void(friction:Float = 0.5)
		Self.fixtureDef.friction = friction
		Self.body.CreateFixture(Self.fixtureDef)
	End
	
	Method SetDensity:Void(density:Float = 1.0)
		Self.fixtureDef.density = density
		Self.body.CreateFixture(Self.fixtureDef)
	End
	
	Method SetRestitution:Void(restitution:Float = 0.1)
		Self.fixtureDef.restitution = restitution
		Self.body.CreateFixture(Self.fixtureDef)
	End
	
	Method SetMass:Void(mass:Float)
		Local md:b2MassData = new b2MassData()
		Self.body.GetMassData(md)
		md.mass = mass
		Self.body.SetMassData(md)
	End
	
	Method SetImage:Void(img:Image)
		Self.img = img
	End
	
	Method Draw:Void()
		if Self.img <> Null
			Local x:Float	= self.body.GetPosition().x * 64
			Local y:Float	= self.body.GetPosition().y * 64
			Local r:Float	= RadToDeg(Self.body.GetAngle()) * -1
			
			DrawImage(Self.img, x, y, r, 1.0, 1.0, 0)
		EndIf
	End
End

Class CWorld
	Field world:b2World
	Field m_velocityIterations:int
    Field m_positionIterations:int
    Field m_timeStep:Float
	
	Field entities:List<CEntity>
	
	Method New(gravityX:Float = 0.0, gravityY:Float = 10.0)
		Self.world = New b2World(New b2Vec2(gravityX, gravityY), True)	
		Self.world.SetGravity(new b2Vec2(gravityX, gravityY))
		
		Self.m_velocityIterations	= 3
		Self.m_positionIterations	= 3
		Self.m_timeStep				= 1.0 / 60.0
		
		Self.entities = New List<CEntity>()
	End
	
	Method update:Void()
		Self.world.TimeStep(self.m_timeStep, self.m_velocityIterations, self.m_positionIterations)
		Self.world.ClearForces()
	End
	
	Method render:Void()
		if Self.entities.Count() > 0
			For Local e:CEntity = eachin self.entities
				if e <> Null e.Draw()
			Next				
		EndIf
	End
	
	Method CreateBox:CEntity(x:Float, y:Float, width:Float, height:Float, static:Bool = false)
		Local entity:CEntity = new CEntity()
		entity.CreateBox(Self.world, x, y, width, height, static)
		Self.entities.AddLast(entity)
		
		Return entity
	End
	
	Method CreateImageBox:CEntity(img:Image, x:Float, y:Float, static:Bool = False)
		Local entity:CEntity = new CEntity()
		entity.CreateImageBox(Self.world, img, x, y, static)
		Self.entities.AddLast(entity)
		
		Return entity
	End
End

Class CTest extends App
	Field world:CWorld
	Field player:Image
	Field player2:Image
	Field playerEntity:CEntity
	Field groundEntity:CEntity
	
	Method OnCreate:Int()
		Self.world 			= New CWorld()
		Self.player			= LoadImage("crate.png",,Image.MidHandle)
		Self.player2		= LoadImage("crate2.png",, Image.MidHandle)
		Self.groundEntity	= Self.world.CreateBox(0, float(DeviceHeight()) / 64.0, float(DeviceWidth()) / 64.0, 40.0 / 64.0, True)
		
		SetUpdateRate(60)
		
		Return 0
	End
	
	Method OnUpdate:Int()
		Self.world.update()
		
		if MouseHit(0) Or TouchHit(0)
			Local mx:Float	= MouseX()/64
			Local my:Float	= MouseY()/64
			Local e:CEntity = self.world.CreateImageBox(self.player, mx, my)		
		EndIf
		
		if MouseHit(1) Or TouchHit(1)
			Local mx:Float	= MouseX()/64
			Local my:Float	= MouseY()/64
			Local e:CEntity = self.world.CreateImageBox(self.player2, mx, my)			
		EndIf
		Return 0
	End
	
	Method OnRender:Int()
		Cls(90, 120, 200)
		#if TARGET = "android"
			DrawText("touch to spwan a new crate", DeviceWidth() / 2, 20, 0.5)
		#Else
			DrawText("left click to spwan a new crate", DeviceWidth() / 2, 20, 0.5)
		#EndIf
		
		Self.world.render()
		
		Return 0
	End
End

Function Main:Int()
	New CTest()
	Return 0
End



skid(Posted 2014) [#63]
It's a pity this very cool thread has to start with confusion. Perhaps the best samples should be moved to code forum?


sionco(Posted 2014) [#64]
Yes, I agree Skid, These code snippits are great, and even sometimes hard to spot, even through searches

As, I didn't see this last post, which has been really helpful.


Paul - Taiphoz(Posted 2014) [#65]
I also agree, I have this thread pinned for the samples, still not done anything with box2D but I do have plans to at some point, so making the samples easier to find gets my vote.