当前位置:网站首页>Egret P2 physical engine (1) small ball falling demo
Egret P2 physical engine (1) small ball falling demo
2022-06-30 06:59:00 【Zmmm Jun】
egret p2 Physics engine learning records
p2(physics) Download address :https://download.csdn.net/download/qq_31189489/79552684
download p2 Physical engine package
\physics\libsrc\bin\physicsCopy all the files in the directory toroot directory /../p2PhysicsUnder the table of contentsModify the project root configuration file
egretProperties.jsonThe amendments are as follows
{ "name":"physics", "path":"../physics" }compile open
egret Editor wingfindplug-in unitegret Project toolsBuild engine[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-CiUikRO8-1644246147802)(attachment:9e3c157f63630e22e7e4397976151e41)]

See if the compilation is successful

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-W7h4V40K-1644246147805)(attachment:5bbf974a7f99351d79a4eff9391377c4)]
If
libs/modules/There is... In the catalog physics Folder indicates that the compilation was successful
Basic concepts
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-H2CHqr3s-1644246147806)(attachment:9cd3b0b7d8e3d3d4fc61b6cffd30e5d3)]

- The world : Set the inside of the world
Acceleration of gravityAdditive elementsadd toWorld related settingsAnd so on , such asSet the friction and correlation coefficient between materials - shape : Draw the basic shape of the object , Every rigid body needs to add a shape , Set up
Shape related propertiessuch as : - rigid body : Set the rigid body ,
Physical related properties, such asRigid body type weightLocation,angular velocity,Locationwait - Mapping :displays, Show by mapping
egretRelated display elements , Binding display
- The world : Set the inside of the world
Basic steps
Create the world
// Instantiate a world object this.world = new p2.World(); // Set up world To sleep this.world.sleepMode = p2.World.BODY_SLEEPING; this.world.gravity = [0,9.8] console.log('create world success')
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-JnhP0XUJ-1644246147808)(attachment:fc678f9cfc7d342956195ddad8872e9e)]
Create a floor
// Draw the ground , through shape and body Two basic objects are combined let stageHeight = egret.MainContext.instance.stage.stageHeight var groundShape:p2.Plane = new p2.Plane() var groundBody:p2.Body = new p2.Body({ type:p2.Body.STATIC, position:[0,stageHeight -100] }) groundShape.material = this.steelMaterial groundBody.angle = Math.PI groundBody.addShape(groundShape) groundBody.displays = [] this.world.addBody(groundBody) // Because there is no bound material , Draw a line directly let groundLine:egret.Shape = new egret.Shape groundLine.graphics.lineStyle(2,0x00ff00) groundLine.graphics.moveTo(0,stageHeight-90) groundLine.graphics.lineTo(egret.MainContext.instance.stage.stageWidth,stageHeight-90) this.addChild(groundLine)[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Pc6II9Ww-1644246147809)(attachment:f9d659f06f55c2597e34d72f82562a75)]

Create a visual ball
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-dr1kU5GJ-1644246147811)(attachment:d4015ba6d3120dfae802b32b9dad9226)]

private display:egret.Shape; private createBody():void{ var boxShape:p2.Shape = new p2.Box({width:20,height:20}) var boxBody:p2.Body = new p2.Body({ mass: 2, position: [200, 200],velocity:[30,5]}) boxShape.material = this.iceMaterial this.display = new egret.Shape() this.display.x = 100 this.display.graphics.beginFill(0xff0000,1) this.display.graphics.drawCircle(0,0,(<p2.Box>boxShape).width) this.display.graphics.endFill() // this.display.width = (<p2.Box>bfoxShape).width // this.display.height = (<p2.Box>boxShape).height boxBody.displays = [this.display] boxBody.addShape(boxShape) this.world.addBody(boxBody) this.addChild(this.display) // var boxShape:p2.Shape = new p2.Shape() // var boxBody:p2.Body = new p2.Body({ mass: 1, position: [200, 180],angularVelocity:1 }) // boxBody.addShape(boxShape) // this.world.addBody(boxBody) console.log('create body success') }Update the view
worldcreated , The motion logic is not automatically executed , Need to pass throughworld.step()Perform a step motion[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-YgTZ2BvM-1644246147813)(attachment:68eb0e172825c999a5b375c373f38e3a)]

this.world.step(1); var l = this.world.bodies.length; for (var i:number = 0; i < l; i++) { var boxBody:p2.Body = this.world.bodies[i]; var box:egret.DisplayObject = boxBody.displays[0]; if (box) { // Assign the coordinates and angles of the rigid body to the display object box.x = boxBody.position[0]; box.y = boxBody.position[1]; // If the current state of the rigid body is sleep , The picture alpha Set to 0.5, Otherwise 1 if (boxBody.sleepState == p2.Body.SLEEPING) { box.alpha = 0.5; } else { box.alpha = 1; } } }Execute all methods in the main program , And the clock function is used to call update function , The final code is as follows
main.ts[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-kk6yiRPA-1644246147815)(attachment:7244415b79b4ba4c1e1a6f77c4df0d1b)]

class HelloWorld extends eui.UILayer{ // Define a world Variable private world:p2.World // Define a debug canvas private debugDraw:any // Define two materials private iceMaterial = new p2.Material(1); private steelMaterial = new p2.Material(2); private async runGame(){ console.log(' load resources ') // Entry method await this.loadResource() // console.log(' Create a background ') // this.createBg() console.log(' Create a gray mask ') this.createMask() // console.log(' draw movieClips') // this.createClips() this.createWorld() this.createGround() this.createBody() this.addEventListener(egret.Event.ENTER_FRAME,this.update,this); } private createClips(){ let data = RES.getRes("chara_json") let textr = RES.getRes('chara_png') let factorys:egret.MovieClipDataFactory = new egret.MovieClipDataFactory(data,textr) let paimeng:egret.MovieClip = new egret.MovieClip(factorys.generateMovieClipData('paimeng')) this.addChild(paimeng) paimeng.gotoAndPlay("main",-1) } // Entry function protected createChildren(): void { super.createChildren() this.runGame() } // Create a background image private createBg(){ let bg = new Util().createBitMap('bg_jpg') console.log(bg) this.addChild(bg) bg.width = this.stage.stageWidth bg.height = this.stage.stageHeight } // load resources private async loadResource() { try { const loadingView = new LoadingUI(); this.stage.addChild(loadingView); // Temporarily annotate preloaded resources // await RES.loadConfig("resource/default.res.json", "resource/"); // await RES.loadGroup("preload", 0, loadingView); this.stage.removeChild(loadingView); } catch (e) { console.error(e); } } // Create a mask private createMask(){ let mask = new egret.Shape() mask.graphics.beginFill(0xffffff,1) mask.graphics.drawRect(0,0,this.stage.stageWidth,this.stage.stageHeight) mask.graphics.endFill() mask.y = 0 this.addChild(mask) } // Create rigid bodies private createWorld():void{ // Instantiate a world object this.world = new p2.World(); // Set up world To sleep this.world.sleepMode = p2.World.BODY_SLEEPING; this.world.gravity = [0,9.8] console.log('create world success') } // Generate floor Plane private planeBody:p2.Body; private createGround():void{ // Draw the ground , through shape and body Two basic objects are combined let stageHeight = egret.MainContext.instance.stage.stageHeight var groundShape:p2.Plane = new p2.Plane() var groundBody:p2.Body = new p2.Body({ type:p2.Body.STATIC, position:[0,stageHeight -100] }) groundShape.material = this.steelMaterial groundBody.angle = Math.PI groundBody.addShape(groundShape) groundBody.displays = [] this.world.addBody(groundBody) // Because there is no bound material , Draw a line directly let groundLine:egret.Shape = new egret.Shape groundLine.graphics.lineStyle(2,0x00ff00) groundLine.graphics.moveTo(0,stageHeight-90) groundLine.graphics.lineTo(egret.MainContext.instance.stage.stageWidth,stageHeight-90) this.addChild(groundLine) // // Build a shape shape // let planeShape:p2.Plane = new p2.Plane(); // // establish body rigid body // this.planeBody= new p2.Body({ // // Rigid body type // type:p2.Body.STATIC, // // The position of the rigid body // position:[0,this.stage.stageHeight] // }); // this.planeBody.angle = Math.PI; // this.planeBody.displays = []; // this.planeBody.addShape(planeShape); // this.world.addBody(this.planeBody); console.log(' create ground success') } private display:egret.Shape; private createBody():void{ var boxShape:p2.Shape = new p2.Box({width:20,height:20}) var boxBody:p2.Body = new p2.Body({ mass: 2, position: [200, 200],velocity:[30,5]}) boxShape.material = this.iceMaterial this.display = new egret.Shape() this.display.x = 100 this.display.graphics.beginFill(0xff0000,1) this.display.graphics.drawCircle(0,0,(<p2.Box>boxShape).width) this.display.graphics.endFill() // this.display.width = (<p2.Box>bfoxShape).width // this.display.height = (<p2.Box>boxShape).height boxBody.displays = [this.display] boxBody.addShape(boxShape) this.world.addBody(boxBody) this.addChild(this.display) // var boxShape:p2.Shape = new p2.Shape() // var boxBody:p2.Body = new p2.Body({ mass: 1, position: [200, 180],angularVelocity:1 }) // boxBody.addShape(boxShape) // this.world.addBody(boxBody) console.log('create body success') } // Frame event , Step function private update() { this.world.step(1); var l = this.world.bodies.length; for (var i:number = 0; i < l; i++) { var boxBody:p2.Body = this.world.bodies[i]; var box:egret.DisplayObject = boxBody.displays[0]; if (box) { // Assign the coordinates and angles of the rigid body to the display object box.x = boxBody.position[0]; box.y = boxBody.position[1]; // If the current state of the rigid body is sleep , The picture alpha Set to 0.5, Otherwise 1 if (boxBody.sleepState == p2.Body.SLEEPING) { box.alpha = 0.5; } else { box.alpha = 1; } } } } // private createDebug():void{ // } // private createTestPhysic():void{ // console.log('create begin') // const body = new p2.Body() // // Create a wide 4 Company 、 high 2 The rectangular shape of the unit // const shpRect: p2.Shape = new p2.Shape({angle:1,position: [200, 180]}); // // Create a flat shape // const shpPlane: p2.Plane = new p2.Plane(); // } }
The pit encountered can be referred to this article : egret p2 Problems encountered by the physical engine (1)
边栏推荐
- Records of problems solved (continuously updated)
- Install the components corresponding to setup
- 【Hot100】11. 盛最多水的容器
- Fastapi learning Day1
- RT thread Kernel Implementation (VI): time slice
- Skillfully use 5 keys to improve office efficiency
- The most complete sentence in history
- ETL为什么经常变成ELT甚至LET?
- memcpy内存重叠的解决
- 6、 Shopping ⻋ and orders
猜你喜欢

IDEA import导入的类明明存在,却飘红?

Fastapi learning Day2

1.2 (supplementary)

1.6 - CPU composition

Steps for formulating class or file templates in idea

InnoDB engine in MySQL

Google Earth engine (GEE) - Murray global tidal wetland change V1 (1999-2019) data set

经纬恒润再次荣获PACCAR集团 10PPM 质量奖

Record one time of Tencent Test Development Engineer's automation interface test practice experience

原理:WebMvcConfigurer 与 WebMvcConfigurationSupport避坑指南
随机推荐
Go项目目录结构介绍
1285_把AUTOSAR函数以及变量等定义的宏用脚本展开以提高可读性
SOC project AHB_ SD_ Host controller design
Mysql5.7 compressed version installation tutorial
File transfer protocol, FTP file sharing server
How does the CPU recognize the code?
【转】存储器结构、cache、DMA架构分析
The solution of memcpy memory overlap
Numpy中的四个小技巧
Several C language implementations
Pay attention to this live broadcast and learn about the path to achieve the dual carbon goal of the energy industry
It turns out that you are such an array. You have finally learned
Notes: environment variables
Ftplib+ tqdm upload and download progress bar
[datawhale team learning] task02: mathematical operation, string and text, list
免实名域名是什么意思?
如果我在珠海,到哪里开户比较好?另外,手机开户安全么?
阿里云买的40G高效云盘挂载只有20G
RT thread Kernel Implementation (VI): time slice
Huawei full-scale Daniel shared the 598 page full-color Manual of network protocols for the first time