当前位置:网站首页>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)
边栏推荐
- 六,购物⻋与订单
- Joseph problem C language
- Which securities company is good for opening a mobile account? Also, is it safe to open an account online?
- First line of code (Third Edition) learning notes
- 成品升级程序
- memcpy内存重叠的解决
- Go常用命令
- Install the components corresponding to setup
- 1.3 - Code System
- Graphic octet, really top
猜你喜欢

First experience of Galaxy Kirin

【Mask-RCNN】基于Mask-RCNN的目标检测和识别

1.9 - Classification of memory

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

MySQL中的InnoDB引擎

【json-tutorial】第一章学习笔记

The most complete sentence in history

Bat 使用细节2

Skillfully use 5 keys to improve office efficiency

记录一次腾讯测试开发工程师自动化接口测试实践经验
随机推荐
1.6 - CPU composition
RT thread application
免实名域名是什么意思?
[transfer] analysis of memory structure, cache and DMA architecture
【docsify基本使用】
Mysql5.7 compressed version installation tutorial
随机网络,无标度网络,小世界网络以及NS小世界的性能对比matlab仿真
ROS-URDF
Record one time of Tencent Test Development Engineer's automation interface test practice experience
Definition and use of ROS topic messages
The 40g high-efficiency cloud disk purchased by Alibaba cloud is only 20g attached
Never forget the original intention, and be lazy if you can: C # operate word files
The most complete sentence in history
【转】存储器结构、cache、DMA架构分析
sscanf 函数的使用
1.4 - fixed and floating point numbers
CPU到底是怎么识别代码的?
File transfer protocol, FTP file sharing server
[my creation anniversary] one year anniversary essay
编写并运行第一个Go语言程序