Today's Messages (off)
| Unanswered Messages (on)
| Forum: Features/Development |
|---|
| Topic: Road Trip approach |
|---|
| | Topic: [Tutorial-4]Create bodies at runtime |
|---|
| [Tutorial-4]Create bodies at runtime [message #5274] |
Thu, 25 April 2013 14:12 |
ladeng6666 Messages: 13 Registered: January 2013 Location: China |
Junior Member |
|
|
In create simple Nape body post, we know how to create simple circle and rectangle bodies. Today, we will dig more deeply to learn how to create simple bodies at run time.
In this post, you will learn how to create body dynamically according to the motion and position of Mouse. The key point to achieve this effect is to calculate the dimension ( like width/height of rectangle and radius of circle ) and position of bodies, and all these information is determined by the position of Mouse, the procedure is basically as below:
- on Mouse down: take a record of the position of Mouse.
- on Mouse move: calculate the dimension according the position of Mouse, like width/height of rectangle and radius of circle.
- on Mouse up: create body using the dimension we calculate at the last move of Mouse.
It is basically like this, the demo below will demonstrate this effect more clearly.
Graphics will start to be draw when you press Mouse button, and when you release the Mouse, a body with same shape will be create and fall to the ground. the shape drawn is rectangle by default, pressing "ctrl" while drawing will create a circle body, pressing "Shift" while drawing will create a regular polygon with 5 edges.
http://www.ladeng6666.com/blog/wp-content/uploads/2012/12/T7 _CreateBodiesOnFly.swf

The source code is as below:
package
{
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.geom.Point;
import nape.geom.Vec2;
import nape.phys.Body;
import nape.phys.BodyType;
import nape.phys.Material;
import nape.shape.Circle;
import nape.shape.Polygon;
import nape.space.Space;
import nape.util.BitmapDebug;
[SWF( width="550", height="400", frameRate="60")]
public class T7_CreateBodiesOnFly extends Sprite
{
private var napeWorld:Space;
private var debug:BitmapDebug;
private var isCtrlDown:Boolean;
private var isShiftDown:Boolean;
private var bodyOnFly:Object;
private var onFlyLayer:Sprite;
public function T7_CreateBodiesOnFly()
{
createNapeWorld();
setUpEvents();
createWall();
//create an object to store the information of bodies
bodyOnFly={x:0, y:0, x1:0, y1:0, w:0, h:0, r:0, mouseAngle:0};
//create a layer to draw shapes at run time.
onFlyLayer=new Sprite();
addChild(onFlyLayer);
addChild(new Stats());
}
//创房Nape世界
private function createNapeWorld():void
{
var gravity:Vec2 = new Vec2( 0, 600 );
napeWorld =new Space( gravity );
debug= new BitmapDebug(550, 400, 0xD6D6D6);
addChild(debug.display);
}
//添加事件侦听
private function setUpEvents():void
{
//listening to the EnterFrame Event to update the Nape world
stage.addEventListener(Event.ENTER_FRAME, loop);
//add listener to MouseEvent,like mouseDown or MouseUp
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseEventHanlder);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseEventHanlder);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyBoardEventHanlder);
stage.addEventListener(KeyboardEvent.KEY_UP, keyBoardEventHanlder);
}
protected function keyBoardEventHanlder(event:KeyboardEvent):void
{
isCtrlDown=event.ctrlKey;
isShiftDown=event.shiftKey;
}
//create several kinds of shape
private function createBody(bodyInfo:Object):void{
if(isCtrlDown){
//如果Ctrl按下,绘制圆形刚体
createCircle(bodyInfo.x, bodyInfo.y, bodyInfo.r, BodyType.DYNAMIC);
}else if(isShiftDown){
//create a regular polygon with 5 edges.
createRegular(bodyInfo.x, bodyInfo.y, bodyInfo.r, bodyInfo.mouseAngle, 5, BodyType.DYNAMIC);
}else{
//and box shape by default
createBox(bodyInfo.x+bodyInfo.w/2, bodyInfo.y+bodyInfo.h/2, bodyInfo.w, bodyInfo.h,BodyType.DYNAMIC);
}
}
private function createBox(posX:Number, posY:Number, w:Number, h:Number, type:BodyType):void{
var box:Body = new Body(type, new Vec2(posX, posY));
var boxShape:Polygon=new Polygon(Polygon.box(w,h), Material.glass());
box.shapes.push(boxShape);
box.space= napeWorld;
}
//create body with specify counts of edge
private function createRegular(posX:Number, posY:Number, r:Number, rotation:Number, edgeCount:int, type:BodyType):void{
var regular:Body = new Body(type, new Vec2(posX, posY));
var regularShape:Polygon=new Polygon(Polygon.regular(r*2,r*2,edgeCount), Material.glass());
regularShape.rotate(rotation);
regular.shapes.push(regularShape);
regular.space= napeWorld;
}
private function createCircle(posX:Number, posY:Number, radius:int, type:BodyType):void
{
var circle:Body=new Body(type, new Vec2(posX, posY));
var shape:Circle=new Circle(radius,null,Material.glass());
circle.shapes.push(shape);
circle.space=napeWorld;
}
private function createWall():void{
createBox(stage.stageWidth/2, 0, stage.stageWidth, 10, BodyType.STATIC);
createBox(stage.stageWidth/2, stage.stageHeight, stage.stageWidth, 10, BodyType.STATIC);
createBox(0, stage.stageHeight/2, 10, stage.stageHeight, BodyType.STATIC);
createBox(stage.stageWidth, stage.stageHeight/2, 10,stage.stageWidth, BodyType.STATIC);
createBox(250, 405, 600,50, BodyType.STATIC);
}
protected function mouseEventHanlder(event:MouseEvent):void
{
switch (event.type) {
case MouseEvent.MOUSE_DOWN:
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseEventHanlder);
//record the position of mouse when it is down
bodyOnFly.x=mouseX;
bodyOnFly.y=mouseY;
break;
case MouseEvent.MOUSE_UP:
stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseEventHanlder);
//to prevent error when the radius is less than 1
if(bodyOnFly.r <1){
bodyOnFly.w=4;
bodyOnFly.h=3;
bodyOnFly.r= Math.sqrt(bodyOnFly.w*bodyOnFly.w + bodyOnFly.h*bodyOnFly.h);
}
//create bodies according to body information
createBody(bodyOnFly);
onFlyLayer.graphics.clear();
break;
case MouseEvent.MOUSE_MOVE:
//calculate the size of rectangle
bodyOnFly.w= mouseX - bodyOnFly.x;
bodyOnFly.h= mouseY - bodyOnFly.y;
bodyOnFly.mouseAngle=Math.atan2(mouseY-bodyOnFly.y, mouseX-bodyOnFly.x);
bodyOnFly.r= Math.sqrt(bodyOnFly.w*bodyOnFly.w + bodyOnFly.h*bodyOnFly.h);
drawShape(bodyOnFly);
break;
}
}
private function drawShape(bodyInfo:Object):void{
var gfc:Graphics=onFlyLayer.graphics;
gfc.clear();
gfc.lineStyle(1);
gfc.beginFill(0x0000FF, 0.5);
if(isCtrlDown){
//when Ctrl is down
gfc.drawCircle(bodyInfo.x, bodyInfo.y, bodyInfo.r);
}else if(isShiftDown){
//when Shift is down
var mouseAngle:Number=bodyInfo.mouseAngle;
var angle:Number = Math.PI*2/5;//the angle between each vertex
var x:Number, y:Number;
//move to the first vertex
gfc.moveTo(bodyInfo.x+bodyInfo.r*Math.cos(mouseAngle), bodyInfo.y+bodyInfo.r*Math.sin(mouseAngle));
for (var i:int=0; i<5; i++){
//calculate each vertex
x=bodyInfo.x + bodyInfo.r * Math.cos( i*angle+mouseAngle);
y=bodyInfo.y + bodyInfo.r * Math.sin( i*angle+mouseAngle);
//连线顶点
gfc.lineTo(x,y);
}
}
else{
gfc.drawRect(bodyInfo.x, bodyInfo.y, bodyInfo.w, bodyInfo.h);
}
gfc.endFill();
}
protected function loop(event:Event):void
{
napeWorld.step(1/60);
debug.clear();
debug.draw(napeWorld);
debug.flush();
}
}
}
Line 97-104: we use the regular() method of Polygon class to create a regular polygon with 5 edges, besides of that, there is box() and rect() using to create a centered rectangle and a customer center point rectangle. more detail information please refer to the API of Polygon.
click to download source code
[Updated on: Thu, 25 April 2013 14:20]
|
|
| | Topic: [Tutorial-3]Understanding Material class |
|---|
| [Tutorial-3]Understanding Material class [message #5064] |
Tue, 26 March 2013 13:24 |
ladeng6666 Messages: 13 Registered: January 2013 Location: China |
Junior Member |
|
|
We mentioned Material class in "Create simple shape" post, but it is not easy to grasp each parameter effectiveness, so today let's study how to use Material class.
Material is a property of Shape class, it is used to set physic property of body, like elasticity, friction etc, to simulate damping movement as real. We could set these property directly in constructor of Material class as below:
public function Material (
elasticity:Number = 0,
dynamicFriction:Number = 1,
staticFriction:Number = 2,
density:Number = 1,
rollingFriction:Number = 0.01
);
The function of each parameters , please refer to the doc of Material class.
We can set and modify the same properties at run time as well, the properties are listed as below:
Besides, Material class provide some static functions, they will return some predefined Material object, you can guess there effectiveness through their names, it's very handful. Actually there is nothing complicated in these methods, just using different configuration of those properties to create a new Material (I guess Luca might have tested for thousands of times to figure out these values, thank you so much.), and return. These static functions are listed in the API of Material.
To make more clear, I create a demo as below, you could modify elasticity, friction and relative properties on the control panel at run time, or using predefined Material by clicking buttons at left side of control panel. click any blank area to create a rectangle body, click while pressing Ctrl key to create a circle body, just try it out, you will see different effectiveness of those properties.
http:// www.ladeng6666.com/blog/wp-content/uploads/2012/11/T6_Create BodyWithMaterial.swf
Learning Nape with ladeng6666
http://ladeng6666.com/
|
|
| | Topic: [Tutorial-2]Create body in simple Shape |
|---|
| [Tutorial-2]Create body in simple Shape [message #4960] |
Fri, 08 March 2013 16:05 |
ladeng6666 Messages: 13 Registered: January 2013 Location: China |
Junior Member |
|
|
In my previous post of "Hello Nape space", we make a quick look at this 2D physics engine, and understand how to create a simple application with Nape. But it's seems too basic, nothing interesting, isn't it? So today, let's start to learn to add something in Nape space.
The "something" I mentioned is called "Body". Actually we have talked about Body in previous tutorial, but it is just a glance, let's learn it a little bit more deeply.
static ,dynamic and kinematic Body
Just like Box2D, from motion point of view, there are 3 types of Body in Nape, which is stored as constant variable in BodyType class, they are BodyType.STATIC ,BodyType.DYNAMIC and BodyType.KINEMATIC. more detail in Nape doc are list as below:
- BodyType.DYNAMIC:Standard dynamic object, this object will be effected by the physics. Think of it as Basketball.
- BodyType.STATIC: Static objects are not permitted to move, and due to this several. Think of it as backboard in NBA.
- BodyType.KINEMATIC: Kinematic objects are static objects which 'are' permitted to move, you wish and are not effected by any physics. We think of it as a special static body, which can move, it can be used as a moving floorer or elevator in platform games.
The type of must be assigned in its constructor, besides, the position of Body is required in constructor as well. Fortunately, it is in pixel, we don't need to make transform (like meter to pixel) as Box2D.
var body:Body = new Body(BodyType.DYNAMIC,new Vec2(bx,by));
Set up the shape of body
The shape of body in Nape could be set up through body.shape property, not like Box2D, this property is a ShapeList instance, that means, we can not assign a Shape instance to this property directly, instead, using body.shape.add() or push() method to add a Shape instance into this list.
There is only on parameter in add() method, it is an instance of Shape class or its sub class(Circle or Polygon) which is what we mostly use in practice. Even there are only two sub class of Shape, but that is not to say only two shape is available for Nape body.
Circle class
Circle class is used to create a circle shape, its constructor is listed as below:
function Circle(
radius:Float,
localCOM:Vec2,
material:Material,
filter:InteractionFilter
)
- radius: the radius of circle, in pixel
- localCOM: the local center of mass,(0,0) by default.
- material: the feature of shape like elasticity, friction are set through material parameter, it is equivalent to b2FixtureDef in Box2D, null by default.
- filter: body collision filter,which kind of body to contact and which kind of body not to contact, just like FilterData class of Box2D
Polygon class
Polygon class will create a polygon shape using vertices specified in localVerts parameter. we could create multiply polygons using different vertices, or we can say any non-circle shape must be created using Polygon class. Its constructor is listed as below:
public function Polygon (
localVerts:*,
material:Material = null,
filter:InteractionFilter = null
);
[LIST TYPE=square]
[*]localVerts: storing all the specified vertices of polygon shape. There are some static function in Polygon class to help us to return the vertices of some simple polygon shape, and what we need to do is just specify the width ,height or radius of these simple shapes. such as Polygon.box() to create a centered rectangle shape.
[*]material: same as in Circle class.
[*]filter: same as in Circle class.
In general, the process to create body is much simpler in Nape than Box2D, we don't need mass of instance like b2Shape,b2FixtureDef,b2Fixture,b2BodyDef and b2Body, it is a really headache to memorize these instance. so Nape is recommended if you are beginner of 2D physics engine.
Back to our topic, after learning Circle and Polygon class , let's start to create some simple circle and rectangle shape(I will introduce more complicated shape in later tutorials).
//create circle shape body
private function createCircle(posX:Number, posY:Number, radius:int, type:BodyType):void
{
//create body, there are 2 parameter of Body class, one is type ,the other is position of body.
var circle:Body = new Body(type, new Vec2(posX, posY));
//create shape of body, currently we only have two: circle and rectangle created using Polygon class
//I will introduce more deeply of Material class in later tutorial
var shape:Circle = new Circle(radius, null, new Material(1));
//shapes property of a body is an instance of ShapeList class, we can add a shape using add() or push() method
circle.shapes.push(shape);
//set up the space of body belonged to
circle.space=space;
}
//create rectangle body, mostly same process with circle body
private function createBox(posX:Number,posY:Number,width:Number,height:Number,type:BodyType, angle:Number=0):Body{
//create body instance
var box:Body = new Body(type, new Vec2(posX, posY));
//get the vertices of a rectangle shape centered at local center of body mass using Polygon.box()
//and then pass these vertices to the constructor of Polygon class.
var shape:Polygon = new Polygon(Polygon.box(width, height));
//rotate the rectangle by angle specified
shape.rotate(angle);
//add rectangle shape in to shape list
box.shapes.push(shape);
//set up the space of Body
box.space=space;
return box;
}
Event we have just add very simple shapes in to Nape world, but it is enough to create a prototype of <Amazing Alex>.

check out the demo by click linkage below;
http://www.ladeng6666.com/blog/wp-content/uploads/2012/11/Si mpleNape.swf
Quote:Hi luca, if you see my tutorial, could please tell me how to upload and swf demo file without outer linkage? thanks
the complete code with comment is as blow:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import nape.phys.Material;
import nape.geom.Vec2;
import nape.phys.Body;
import nape.phys.BodyType;
import nape.shape.Circle;
import nape.shape.Polygon;
import nape.space.Space;
import nape.util.Debug;
import nape.util.ShapeDebug;
//[SWF(frameRate="60", width=550, height=400, backgroundColor="0xCCCCCC")]
public class Main extends Sprite
{
private var space:Space;
private var debug:ShapeDebug;
public function Main()
{
//1. create Nape space
var gravity:Vec2=new Vec2(0,500);
space=new Space(gravity);
//2. create debug shape
debug = new ShapeDebug(550, 400, 0x0000ff);
addChild(debug.display);
//3. create bodies in game
createBodies();
//add FPS monitor on left top corner
addChild(new Stats());
//4.add enterFrame event listener
addEventListener(Event.ENTER_FRAME,loop);
}
private function createBodies():void
{
//upper 3 floor
createBox(92, 130, 120, 15, BodyType.STATIC,Math.PI/6);
createBox(208, 163, 120, 15, BodyType.STATIC);
createBox(350, 163, 144, 15, BodyType.STATIC);
//lower 3 floor
createBox(483, 223, 120, 15, BodyType.STATIC,-Math.PI/6);
createBox(360, 255, 120, 15, BodyType.STATIC);
createBox(232, 255, 120, 15, BodyType.STATIC);
//the hook at left down corner
createBox(49, 297, 15, 70, BodyType.STATIC);
createBox(157, 297, 15, 70, BodyType.STATIC);
createBox(100, 325, 120, 15, BodyType.STATIC);
//2 books on floor
createBox(200, 120, 15, 100, BodyType.DYNAMIC);
createBox(300, 120, 15, 100, BodyType.DYNAMIC);
//create the falling ball
createCircle(59, 28, 17, BodyType.DYNAMIC);
createCircle(422, 130, 17, BodyType.DYNAMIC);
}
//create circle shape body
private function createCircle(posX:Number, posY:Number, radius:int, type:BodyType):void
{
//create body, there are 2 parameter of Body class, one is type ,the other is position of body.
var circle:Body = new Body(type, new Vec2(posX, posY));
//create shape of body, currently we only have two: circle and rectangle created using Polygon class
//I will introduce more deeply of Material class in later tutorial
var shape:Circle = new Circle(radius, null, new Material(1));
//shapes property of a body is an instance of ShapeList class, we can add a shape using add() or push() method
circle.shapes.push(shape);
//set up the space of body belonged to
circle.space=space;
}
//create rectangle body, mostly same process with circle body
private function createBox(posX:Number,posY:Number,width:Number,height:Number,type:BodyType, angle:Number=0):Body{
//create body instance
var box:Body = new Body(type, new Vec2(posX, posY));
//get the vertices of a rectangle shape centered at local center of body mass using Polygon.box()
//and then pass these vertices to the constructor of Polygon class.
var shape:Polygon = new Polygon(Polygon.box(width, height));
//rotate the rectangle by angle specified
shape.rotate(angle);
//add rectangle shape in to shape list
box.shapes.push(shape);
//set up the space of Body
box.space=space;
return box;
}
private function loop(event:Event):void
{
//Nape simulation
space.step(1 / 60);
//clear debug shape
debug.clear();
//draw all the stuffs in space
debug.draw(space);
//optimize display
debug.flush();
}
}
}
[Updated on: Fri, 08 March 2013 16:14] Learning Nape with ladeng6666
http://ladeng6666.com/
|
|
| | Topic: [Tutorial-1] Hello Nape Space |
|---|
| [Tutorial-1] Hello Nape Space [message #4942] |
Sat, 02 March 2013 14:46 |
ladeng6666 Messages: 13 Registered: January 2013 Location: China |
Junior Member |
|
|
Hi, everybody, I am ladeng6666 from Chinese, a fans of Nape Engine, I like Nape, I like share tutorial with others more, so I write a serial tutorial. you can get an preview at my blog.
http://www.ladeng6666.com/blog/category/nape/
I said "preview", because these posts are written in Chinese, don't worry, I will translate into English gradually and post there, hope you will like it.
let's start to learn Nape!
Welcome to contact with me by email: ladeng6666.chen@gmail.com[/email]
============================================================ ======
Nape is a Physic game library besides Box2D, it is written by Luca Deltodesco with Haxe. Fortunately, Luca prepared a SWC of Nape for our ActionScirpt programmer, thanks Luca, and this is what I am using in this serial tutorial, click here to get the SWC file in official site.
Compared with Box2D, Nape is faster and more efficient, and more powerful, high-level callback system, these are all introduced in official site, more information from here.
The concept of Nape is mostly same with Box2D, if you don't know how to use Box2D, you can start from knowing b2World from here, but it is not necessary. If you are familiar with Box2D, congratulations, you are grasp the basic knowledge of Nape based on Box2D in a few minutes. well, let's start to learn how to create a simple Nape application.
1. Space , the world of Nape
Class Space build the physic simulation environment for Nape, the environment is like the earth we live in, and Space is the core of any Nape application.
Quote:You can think of Space as the b2World class of Box2D engine.
As a physic engine, gravity is a necessary element. Gravity in nape is indicated as instance of Vec2 class, so the code to create a Nape space is list as below:
//1.create a basic Nape space
//declare the gravity of Nape space
var gravity:Vec2 = new Vec2(0, 400);
space = new Space(gravity);
After create the Space of Nape, we need to simulate the physic movement by call the space.step() method, it will calculate all the physic information of body(I will explain body) ,like position, rotation , vertices of polygon; it is a very complicated process, thanks to Luca again from the deep of my heart. Calling space.step() method continuously in ENTER_FRAME event hanlder, then all of the physic information will be calculated automatically. we don't need to worry about this process.
there are 3 parameters in step() method, their functions are listed as below:
deltatime: the interval between current and previous calculation, the shorter this time , the more precise of collision detect, and the more CPU it will cost meanwhile, so you need to balance precise and efficiency when set this parameter, mostly I will set it to be 1/60.
velocityIterations: iterate time of velocity during collision detect, 10 by default.
positionIterations: iterate time of position during collision defect, 10 by default.
so we can call space.step() method at most of time as below:
//Nape space simulation using step method
space.step(1 / 60);
2. Create Nape Body
Now we have a Nape space, it is time to add something in it, just as Box2D, we call this "something" as body in Nape.After created and added in to Space, it's position, velocity and relative physic property will be calculated by Nape engine automatically. This concept is mostly same with Box2D.
There are 3 step to create a Body instance:
1. Create a Body instance, and set its type and position. The type of a Body is indicated by the 3 constant variables in BodyType class, which are BodyType.STATIC , DYNAMIC and KINEMATIC. position of a body is a Vec2 instance.
2. Create a Shape instance for body to represent the shape of it, the type of this shape can be Circle or Polygon, more non-circle shape could be created with different vertices by Polygon. and bind it with body using body.shapes.add() method.
3. Indicate the Space of body by assigning a Space instance to Body.space property..
Take for instance:
// 1.create a body instance and set its type and position properties.
var body:Body = new Body(BodyType.DYNAMIC, new Vec2(mouseX, mouseY));
// 2.Create s Shape instance for body, here we use Polygon.box() method to return a Vector with 4 vertices to represent an rectangle. Finally add this shape into body.shapes list.
var shape:Polygon = new Polygon(Polygon.box(Math.random()*30+30,Math.random()*30+30));
body.shapes.add(shape);
// 3.Indicate the Nape space of Body
body.space = space;
3. Create Nape debug shape
We still can not see anything on stage , even we have finished those 2 steps above, because neither space or body is display object. To solve this problem, we need to create a ShapeDebug instance, it will iterate all the bodies in Nape space, and draw them into a DisplayObject using Graphics API of AS3.0, then we can get this DisplayObject with ShapeDebug.display property, and add it on stage, after this ,we can see what we have created above.
Quote:We can think of ShapeDebug as b2DebugDraw in Box2D
There are 3 parameters in ShapeDebug constructoer, the first two indicate the width and height of ShapeDebug, the third one represent background color of ShapeDebug.
Then we call clear(), flush() and draw() method of ShapeDebug to clear display, optimize display and draw Nape bodies.
Take an example as below:
//3.create Nape debug shape
debug = new ShapeDebug(400, 200);
addChild(debug.display);
private function loop(e:Event):void
{
// simulate physic calculation with step method
space.step(1 / 60, 30);
// clear display
debug.clear();
// optimize display
debug.flush();
// draw all the object in space, including bodies , joints etc.
debug.draw(space);
}
4. A simple example.
Up to here, we have learned all the necessary knowledge to create a simple Nape application, the demo is as below, click to create a body at mouse position.
http://www.ladeng6666.com/blog/wp-content/uploads/2012/09/Na peTest.swf
completed code is as below:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import nape.geom.Vec2;
import nape.phys.*;
import nape.shape.Polygon;
import nape.space.Space;
import nape.util.ShapeDebug;
/**
* ...
* @author ladeng6666
*/
public class HelloNape extends Sprite
{
private var space:Space;
private var debug:ShapeDebug;
public function HelloNape()
{
var gravity:Vec2 = new Vec2(0, 400);
space = new Space(gravity);
var body:Body = new Body(BodyType.STATIC, new Vec2(stage.stageWidth/2, stage.stageHeight-10));
var shape:Polygon = new Polygon(Polygon.box(stage.stageWidth, 10));
body.shapes.add(shape);
body.space = space;
debug = new ShapeDebug(400, 200);
addChild(debug.display);
addEventListener(Event.ENTER_FRAME, loop);
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseEventHandler);
}
private function mouseEventHandler(e:MouseEvent):void
{
var body:Body = new Body(BodyType.DYNAMIC, new Vec2(mouseX, mouseY));
var shape:Polygon = new Polygon(Polygon.box(Math.random()*30+30,Math.random()*30+30));
body.shapes.add(shape);
body.space = space;
}
private function loop(e:Event):void
{
space.step(1 / 60, 30);
debug.clear();
debug.flush();
debug.draw(space);
}
}
}
[Updated on: Sat, 02 March 2013 14:53] Learning Nape with ladeng6666
http://ladeng6666.com/
|
|
| | Topic: Visually create compound bodies using JSFL Flash |
|---|
| Visually create compound bodies using JSFL Flash [message #3833] |
Tue, 16 October 2012 15:39 |
ptc79 Messages: 1 Registered: October 2012 Location: London |
Junior Member |
|
|
It can be tedious creating compound bodies with code, adding all the joints, shapes etc. I was wondering if anyone has created a plugin for Flash that allows you to do it visually.
It would be a real time saver to have a tool in the Flash Pro IDE that allowed you to add joints to movieclips, then ran a Nape simulation of the physics in real time. It could then export the AS for the Nape bodies, or some XML.
Does anyone know of a plugin like this, or a way to save time when creating compounds/bodies?
This should be in the help section, sorry about that.
[Updated on: Tue, 16 October 2012 15:41]
|
|
| | Topic: Particle System + Nape |
|---|
| Particle System + Nape [message #3731] |
Sun, 23 September 2012 19:41 |
Renat Messages: 52 Registered: May 2012 Location: Russia |
Member |
|
|
|
Is there a particle system engine works in conjunction with Nape?
[Updated on: Sun, 23 September 2012 19:43]
|
|
| | Topic: Body::constraints modification |
|---|
| Body::constraints modification [message #2728] |
Sat, 28 April 2012 18:40 |
dELtaluca Messages: 2228 Registered: July 2010 Location: Malden Rushett, Surrey |
Senior Member Administrator |
|
|
At present, Body::callbacks list only contains those constraints which are both inside of a space AND active.
I propose to change this so that it instead tracks those constraints which are inside of a space whether the constraint is active or not. Mainly because it gives the ability to compute 'connected' bodies following constraints properly.
-----------
On a side note, I would like to hear what people think about Constraint.ignore. At present, if a constraint is not 'active', then it is not considered when deciding if two shapes should interact. Should this be changed so that like with the constraints list on body, any constraint in the space 'whether active or not' is considered with it's ignore property?
I created nape!
|
|
| | Topic: Milestone 5 - Examples |
|---|
| Milestone 5 - Examples [message #899] |
Mon, 06 June 2011 13:10 |
dELtaluca Messages: 2228 Registered: July 2010 Location: Malden Rushett, Surrey |
Senior Member Administrator |
|
|
Simple example of constructing a chain of diamonds using pivot joints or soft distance joints, assign debug graphics to the objects rather than doing a debug draw, however use the debug draw to draw constraints.
var pivots = true;
var pre = space.world;
for(i in 0...30) {
var box = new Body();
box.position.setxy(300,50+i*15);
box.shapes.add(new Polygon(Polygon.regular(24,14,4)));
box.space = space;
box.velocity.x = i*20;
addChild(box.graphic = Debug.createGraphic(box));
var anchor1 = if(pre==space.world) new Vec2(300,35)
else new Vec2(0,7);
var con:Constraint;
if(pivots) con = new PivotJoint(pre,box,anchor1, new Vec2(0,-7));
else {
con = new DistanceJoint(pre,box,anchor1, new Vec2(0,-7), 2,2);
con.stiff = false;
con.frequency = 5;
con.damping = 0.5;
}
con.space = space;
pre = box;
}
var debug = new Debug();
debug.drawBodies = false;
debug.drawConstraints = true;
// in update {
space.step(1/60,6,6);
graphics.clear();
debug.draw(graphics,space);
// }
Results:
stiff pivot joints
soft distance joints
I created nape!
|
|
| | Topic: Holidays |
|---|
| Holidays [message #504] |
Mon, 03 January 2011 11:17 |
dELtaluca Messages: 2228 Registered: July 2010 Location: Malden Rushett, Surrey |
Senior Member Administrator |
|
|
I would have posted this earlier but didn't foresee my lack of internet access of the holidays.
I will continue after today to have no internet access until the 17th january (As I am and will still be spending the christmas break with my parents away from any decent internet connection, and will be skiing in the coming week with no internet access whatsoever)
I created nape!
|
|
| | Forum: Help! |
|---|
| Topic: How to approach "Crouching" in platformer with nape? |
|---|
| How to approach "Crouching" in platformer with nape? [message #5412] |
Sat, 25 May 2013 15:52 |
NucInt Messages: 11 Registered: March 2013 |
Junior Member |
|
|
As in title.
Because obviously crouched hitbox would be of 1/2 of char height. how to approach problems like standing on moving platform, going under some small passage , and if player stops crouyching then what? he will get pushed off?
Im kinda quite lost how to approach it:
1. from nape physics perspective - swap two different bodies on fly? Wont it break physics in some way? compose it and set one shape filters to ignore everything?
2. how to deal with gameplay implications.
Im probably going to drop this in next game as this is quite complex. but still im interested in how people see this.
|
|
| | Topic: Problem with constraints |
|---|
| | Topic: Body Elasticity and Constraints |
|---|
| Body Elasticity and Constraints [message #5409] |
Thu, 23 May 2013 08:29 |
pflores Messages: 3 Registered: February 2013 Location: United States |
Junior Member |
|
|
I've searched all over the forum and documentation, but can't find an answer for this...
I have two bodies that each consist of a shape with a material elasticity of 1.0. The two bodies are attached using a WeldJoint. I noticed that when ONLY ONE of the bodies first collides with a surface, the two bodies as a whole do not bounce; however, when both bodies touch a surface at the same time or when one of the bodies touches a surface while the other is already touching the surface, then the two bodies will bounce.
I thought it might have been something I was doing, but then I took the official Constraints sample and added a Material to each shape/body with an elasticity of 1.0, and saw the same result.
Anyone know what's going on here? Thanks!
|
|
| | Topic: Platformer with Nape |
|---|
| Platformer with Nape [message #5399] |
Tue, 21 May 2013 13:57 |
LearningLabber Messages: 1 Registered: May 2013 |
Junior Member |
|
|
Hello.
First of all, I want to say I'm quite a beginner, please bare with me.
I want to create a platformer with nape, yes I do realize that platformers does not really behave in any way physics-y, but I'm trying to create a physics-heavy platformer akin to Limbo.
The problem I'm having however is implementing slopes in my game, such as seen here: http://codepen.io/jordanranson/pen/ckIso
Basically:
rotate based on the angle of slope
don't fly (when very fast an uphill slope will make the circle fly instead of sticking with the line.)
I've used Emanuele's hill code to generate, well, hills.
I've 'copied this snippet, which I hoped would solve my rotate based on angle of slope problem.
this.collide = function(line, adjx, adjy) {
var run = line.x2 - line.x1;
var rise = line.y2 - line.y1;
var angle = radToDeg(Math.atan(rise / run));
this.rotation -= angle
Where this.rotation is a setter and runs body.rotate(). I just realized I can't simply edit the angle of my body, instead using body.rotate. I'm not sure if -= is the way to go though.
It produces quite weird behavior though, it seems to rotate not on the center and just rotate everywhere.
If anyone can point me to the right direction it'd be heavenly. Excuse me for my noobness.
|
|
| | Topic: Erasing correct parts of destructible terrain |
|---|
| | Topic: Beginner problem |
|---|
| Beginner problem [message #5213] |
Wed, 17 April 2013 22:19 |
Jazza Messages: 5 Registered: April 2013 |
Junior Member |
|
|
For the first Nape example, I made an hxml file:
-swf test.swf
-main BasicSimulation
-lib nape
But it says 'Class not found: BasicSimulation,' even though it's right there in the code...
edit:
Well, just as I was about to post, I figured out the problem... the file name has to be the same as the main class name. Maybe this post will save someone else the trouble
|
|
| | Topic: sorting Vertex |
|---|
sorting Vertex [message #5193] |
Sat, 13 April 2013 20:15 |
|
Ok, maybe not entirely related to the engine, but i want to show a correct representation of a vertex in a shape.
A have a list of Vec2, each time i add a "vertex dot", is added to the end of the list.
I'm looping through the array to display the shape with graphics.moveTo / lineTo
When i want to add a new vertex over an edge, sometimes the drawing "breaks", generating an intersection... so, I need to find the "correct" index for that new vertex based on the "nearest" vertex at the same edge.
I tried to find the nearest vertex (without considering the edges), obviously the results, most of the time, are incorrect.
I just need to find the correct index in the array to add the new "dot".
I'm trying to replicate PhysicsEditor's behaviour when u draw polys.
Expected behaviour
Hope to be clear enough 
Thanks!
|
|
| | Topic: destructive terrain |
|---|
| destructive terrain [message #5028] |
Wed, 20 March 2013 06:57 |
hellopaso Messages: 1 Registered: March 2013 |
Junior Member |
|
|
Hello there,
I am creating game similar to
http://www.youtube.com/watch?v=OjBBlQ1Kjkw
Some questions:

1) What is the best way to do movement?
(first image, red circle is Enemy that have to move from left to right)
I checked that setting velocity in enterFrame work fine,
but there are cases (e.g. 90degrees obstacles) that it stops working.
2)Image 2 and 3 (green stroke)
How to get rid of such "dirty" spaces?
(after explosiion)
so that terrain looks more natural.
thanks
[Updated on: Wed, 20 March 2013 07:01]
|
|
| | Topic: Find edge with raycast |
|---|
| Find edge with raycast [message #4885] |
Sat, 23 February 2013 15:15 |
robohead Messages: 8 Registered: February 2013 |
Junior Member |
|
|
Hi,
i have a body with multiple shapes (see image). There are two things where i could use some help.

1. I want to find the 'edge a' with the 'raycast A'. The RayResult just gives me the shape (polygon). Do i have to iterate the edges of the polygon and check witch one intersects the ray, or is there an easier way?
2. What would be the best technique to find the edges 'c','d' and 'e' if i start with 'edge b'? Use shapesUnderPoint() at the end points of the first edge, iterate through the shape edges and compare the endpoints with my initial endpoint? sounds complicated :/
Thank you
|
|
| | Topic: Center of Mass problems with shapes from destructible terrain |
|---|
| Center of Mass problems with shapes from destructible terrain [message #4869] |
Thu, 21 February 2013 06:51 |
dialectric Messages: 16 Registered: February 2013 Location: USA |
Junior Member |
|
|
center of mass
I've been working off of the destructable terrain demo code, and, after breaking up the entire terrain into Dynamic bodies, am having a problem with shapes' centers of mass not being at the center of the shape.
I am using a custom image instead of the perlin noise. The terrain computing code is unchanged. I take the output and copy each shape to a new dynamic body in a 2nd space, then clear the original space.
As the simulation runs, the squares break apart as intended, but fall wrong, sort of a pendulum swinging effect, as if their center of mass is the top left corner of the stage or at least positioned off of the shape visible in the debugger. aShape.localCOM returns 0,0 for all of the shapes. I tried setting it with
aShape.localCOM.setxy(aShape.bounds.width/2, aShape.bounds.height/2);
but that made things worse.
What is the best way to ensure bodies created with 1 shape each always have the center of mass at the center of the shape?
- dialectric
[Updated on: Thu, 21 February 2013 06:52]
|
|
| | Topic: help :) |
|---|
| help :) [message #4414] |
Fri, 28 December 2012 01:36 |
|
fixed stupid mistake
[Updated on: Fri, 28 December 2012 01:45]
|
|
| | Topic: Create a top-down truck with a trailer |
|---|
| Create a top-down truck with a trailer [message #3704] |
Thu, 20 September 2012 18:10 |
FluFme Messages: 1 Registered: September 2012 |
Junior Member |
|
|
Hi!
I need to create a truck with a trailer.
So, controlling a truck I have no idea how to apply forces correctly.
This
var accelerate:Vec2 = new Vec2();
const angleInc:Number = 0.06;
if (Key.isKeyDown(Keyboard.LEFT)) {
_angle += angleInc;
}
if (Key.isKeyDown(Keyboard.RIGHT)) {
_angle -= angleInc;
}
if (Key.isKeyDown(Keyboard.UP)) {
const power:int = 10;
accelerate.x = Math.cos(_angle) * power;
accelerate.y = Math.sin(_angle) * power;
}
body.rotation = _angle;
body.applyWorldImpulse(accelerate);
apply a slide effect, not drive.
With trailer - I need to use joints, of course. Maybe, there will not be any problem's, but it's hard to talk about it unless the truck drives 
Thanks, and sorry for my bad english.
[Updated on: Thu, 20 September 2012 18:17]
|
|
| | Topic: The missile example |
|---|
| The missile example [message #2699] |
Tue, 24 April 2012 10:15 |
AmiFlash Messages: 93 Registered: January 2012 |
Member |
|
|
Hello,
i'm quite sure i saw some interesting demo by an user (i don't remember his name). One of these demos shows a missile whose trajectory was controlled by the mouse.
Do you know where i can find?
thank you
|
|
| | Topic: Will Nape use domain memory? |
|---|
| | Topic: Model of thread |
|---|
| Model of thread [message #936] |
Fri, 17 June 2011 08:25 |
Manekineko Messages: 2 Registered: June 2011 |
Junior Member |
|
|
Maybe someone had to deal with this problem?
I want to make a physical model of the thread. Do this by using a sequence of particles. Particles compound joints. As a result, I have two problems:
1. The thread is greatly varies, with any parameters of elasticity. It's not like a thread in the real world.
2. When the thread is spreading over the obstacle, the obstacle passes through the thread, between the joints.
Has anyone encountered this problem?
With what tools can I do thread model?
|
|
| | Topic: Default kinetic values or what is it? |
|---|
| Default kinetic values or what is it? [message #921] |
Thu, 09 June 2011 16:13 |
flash2you Messages: 14 Registered: June 2011 |
Junior Member |
|
|
Hello,
i have a little problem.
looks like all my objects moves/after colision in left. (dont know why?)
i specially created a simple test file.
here is code:
package
{
import flash.Boot;
import flash.display.Sprite;
import flash.events.Event;
import nape.geom.AABB;
import nape.geom.Vec2;
import nape.phys.Material;
import nape.phys.PhysObj;
import nape.space.UniformSleepSpace;
import nape.util.Tools;
public class Test extends Sprite
{
private var gravity:Vec2
private var space:UniformSleepSpace;
private var physObj:PhysObj;
public function Test()
{
new Boot()
gravity = new Vec2(0, 100);
space = new UniformSleepSpace(new AABB(0, 0, 750, 500), 30, gravity);
physObj = Tools.createBox(250, 300, 400, 20, 0, 0, 0, true, Material.Steel)
addChild(physObj.graphic)
space.addObject(physObj)
physObj = Tools.createBox(250, 0, 20, 100, 0, 0, 0, false, Material.Steel)
addChild(physObj.graphic)
space.addObject(physObj)
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(e:Event = null):void
{
space.step(1 / 30, 4, 4);
}
}
}
so Stick that moves down, always fall in left(!) after colision.
is looks like its has a small wind or something.
i am noticed that sometimes if i after some time add to object
"smoment" = 0 then its will move down, but not fall. but its not works always.
thanks
|
|
| | Forum: Bugs |
|---|
| Topic: Constraints |
|---|
Constraints [message #2078] |
Thu, 23 February 2012 21:53 |
XELAD Messages: 8 Registered: February 2012 Location: Russia |
Junior Member |
|
|
Hello!
I've spent half a day to understand what kind of Constraint I really need.
The idea is:
1) Two bodies.
2) Fixed distance between them (may be even 0)
3) Point of rotation of body = [0, 0]
3) NOT fixed rotation of themselves, no dependence.
First I tortured WeldPoint, then PivotPoint, then thought about UserConstraint...
The solution was DistanceJoint.
Please, mention it somewhere!
|
|
| | Topic: Bad PreBegin Detection |
|---|
| Bad PreBegin Detection [message #841] |
Wed, 27 April 2011 14:55 |
kiloT Messages: 4 Registered: April 2011 Location: Russia |
Junior Member |

|
|
here is my code of body creation
body = new Body(x, y);
var array:Array = [[[23.75, -13.3], [18.1, -12.5], [ -17.85, -12.75], [ -24.4, -13.75], [ -26.45, -21.7], [24.9, -21.95]], [[ -17.85, -12.75], [18.1, -12.5], [13.95, 22.4], [ -13.6, 22.55]]];
fromArrayToBody(array, body, mc.scaleX, mc.scaleY, Material.Tire);
var remover_box:Shape = createBoxShape((-1) * mc.scaleX, (-20) * mc.scaleY, 37 * mc.scaleX, 20 * mc.scaleY, null, 0x000001);
remover_box.cbType = FLOWER_TYPE;
body.addShape(remover_box);
body.setAngle(angle / k);
body.calcProperties();
body.update();
world.addObject(body);
body.assignGraphic(mc);
if I add to the space PreBegin something like that:
world.addCbPreBegin(WATER_TYPE, FLOWER_TYPE, collisionWaterFlower);
space don't detect collision between this two bodies.
But if i add something like that:
world.addCbPreBegin(CbType.DEFAULT, FLOWER_TYPE, collisionWaterFlower);
and in collisionWaterFlower add own comparison:
private function collisionWaterFlower(arbiter:Arbiter):int
{
if (arbiter.b1.cbType != WATER_TYPE && arbiter.b2.cbType != WATER_TYPE) return Callback.IGNORE; //this is my comparison
var b1:PhysObj = arbiter.b1;
var b2:PhysObj = arbiter.b2;
if (b1.graphic.name == "WaterDrop")
{
removedObjects.push(b1);
(b2.graphic as Flower).addWaterDrop();
}
else
{
removedObjects.push(b2);
(b1.graphic as Flower).addWaterDrop();
}
return Callback.IGNORE
}
it works fine. May be this is not bug (may be this is the feature ), but look like this.
Sorry for my broken english 
here is other function:
public function createWaterDrop(pos:Vec2, vel:Vec2, radius:Number = 0)
{
var waterDrop:MovieClip = new WaterDrop();
waterDrop.x = pos.px;
waterDrop.y = pos.py;
GameManager.instance.game.currentLevel.water.addChild(waterDrop);// as MovieClip;
waterDrop.name = "WaterDrop";
var waterMaterial:Material = new Material(0.3, 0, 0, 1);
var body:Body = Tools.createCircle(randomInt(waterDrop.x-radius, waterDrop.x+radius), randomInt(waterDrop.y-radius, waterDrop.y+radius), waterDrop.width * 0.3,
vel.px, vel.py, 0, false, false, waterMaterial, 0x000001);
body.cbType = WATER_TYPE;
body.assignGraphic(waterDrop);
world.addObject(body);
if (GameManager.instance.game.score > 0)
{
GameManager.instance.game.score --;
GameManager.instance.game.refreshScore();
}
}
private var FLOWER_TYPE:int = CbType.get();
private var WATER_TYPE:int = CbType.get();
[Updated on: Wed, 27 April 2011 14:58]
|
|
| | Forum: Community Creations |
|---|
| Topic: New game release: Abyss Trap |
|---|
| | Topic: Inba in the App Store real soon! (March 30th) |
|---|
| | Topic: Citrus Engine on Nape with Starling |
|---|
| Citrus Engine on Nape with Starling [message #3256] |
Fri, 13 July 2012 14:47 |
Aymeric Messages: 20 Registered: July 2012 |
Junior Member |
|
|
The Citrus Engine is an AS3 2D Game Engine. It support several display renders : classical flash display list, blitting & Stage3D thanks to Starling. It is built as a "platformer" starter-kit using Box2D physics engine.
I'm glad to say that now you can also use Nape!!
It also has a port on Haxe NME (but not ready for production).
More information there.
|
|
| | Topic: [ESCAPE ROCKET HD] |
|---|
| | Topic: Nape on mobile platform |
|---|
| | Topic: Physics Puzzle Maker |
|---|
| | Topic: Byti! My first Nape physics Game |
|---|
| Byti! My first Nape physics Game [message #594] |
Mon, 07 February 2011 11:10 |
DavidABrown85 Messages: 1 Registered: February 2011 Location: Cardiff |
Junior Member |
|
|
Hey Nape Community,
I have been experimenting with Nape for the last few weeks and have have been amazing how much you can get out of the engine.
I have published the first level of the game. which you can find here:
http://stwnsh.s4c.co.uk/en/gemau/byti
The concept is to play as a rugby ball called "Byti" who wants to be the most famous ball in the world... So you basically have to fire him into the spotlight of the other balls 
I'm going to release a new level each week, each with its own theme.
The current themes will be:
- Bowling (published) - Cricket ( as good as ready) - Baseball ( developing ) - Golf ( planning ) - Football (planning )
The cricket level will have wickets, swinging cricket bats and falling balls.
but the other levels are still up for debate, if anyone has any more ideas I would love to hear them.
I'm really impressed with the Nape physics engine, it really has done most of the work for me. keep up the amazing work!
|
|
| | Topic: The official Bold Pixel thread |
|---|
| The official Bold Pixel thread [message #246] |
Fri, 01 October 2010 16:27 |
VortixGames Messages: 26 Registered: August 2010 |
Junior Member |
|
|
With phase 1 of the wrapper done, it's time to show off what we want to achieve with this wrapper. The wrapper will be released with the public version of Bold Pixel, as soon as our current project is finished.
Underneath the Bold Pixel physics package is Nape. There's nothing fancy or magical about it, it's just a bunch of Nape's code. Coding a wrapper only makes sense if there are some specific objectives:
1. All the stuff that needs to be done when something is changed in Nape should need one line only. So if changing position of a kinematic object, the velocity is automatically calculated or when changing a material, all shapes get the new material (more on this later)
2. Simplified processes following the convention over configuration ideal. This means that the wrapper is less powerful out of the box than Nape itself, but methods are provided to allow access to all the important stuff.
3. Presets! All entities (bodies in Nape lingo ) are presets of some behavior we want to achieve. The wrapper is supposed to give support to the simple direct stuff that lies in a abstract class. Each preset is supposed to extend that abstract class in order to automate most processes.
This is the main idea for now, more to come with demos and discussion, but here's a demo, click the stage to repeat the simulation: http://megaswf.com/serve/53825/
In it there's a core wrapper (the engine itself), a bunch of abstract entities (boxes and balls) with some materials, core walls (a preset to create debug walls) and a explosive (a preset that triggers a explosion).
[Updated on: Fri, 01 October 2010 16:28]
|
|
|
Current Time: Sun May 26 03:56:32 BST 2013
Total time taken to generate the page: 0.02658 seconds
|