Commit 01ff34fa authored by wildfirecode's avatar wildfirecode

1

parent 9913d662
File added
No preview for this file type
{
"version": "0.2.0",
"configurations": [
{
"name": "Wing 内置播放器调试",
"type": "chrome",
"request": "launch",
"file": "index.html",
//"url": "http://mysite.com/index.html",
"runtimeExecutable": "${execPath}",
"sourceMaps": true,
"webRoot": "${workspaceRoot}",
"preLaunchTask":"build",
"port":5864
},
{
"name": "使用本机 Chrome 调试",
"type": "chrome",
"request": "launch",
"file": "index.html",
//"url": "http://mysite.com/index.html",
"runtimeExecutable": "",
"sourceMaps": true,
"webRoot": "${workspaceRoot}",
"preLaunchTask":"build",
"userDataDir":"${tmpdir}",
"port":5864
}
]
}
\ No newline at end of file
{
"version": "0.1.0",
"command": "egret",
"isShellCommand": true,
"tasks": [
{
"taskName": "build",
"showOutput": "always",
"args": [
"build",
"-sourcemap"
],
"problemMatcher": "$tsc"
},
{
"taskName": "clean",
"showOutput": "always",
"args": [
"build",
"-e"
],
"problemMatcher": "$tsc"
},
{
"taskName": "publish",
"showOutput": "always",
"args": [
"publish"
],
"problemMatcher": "$tsc"
}
]
}
\ No newline at end of file
......@@ -24,9 +24,11 @@
</head>
<body>
<div style="margin: auto;width: 100%;height: 100%;" class="egret-player" data-entry-class="Main" data-orientation="auto"
data-scale-mode="showAll" data-frame-rate="30" data-content-width="750" data-content-height="1624" data-multi-fingered="2"
data-show-fps="false" data-show-log="false" data-show-fps-style="x:0,y:0,size:12,textColor:0xffffff,bgAlpha:0.9">
<div data-entry-class="TestAsset"
style="margin: auto;width: 100%;height: 100%;" class="egret-player"
data-orientation="auto" data-scale-mode="showAll" data-frame-rate="60" data-content-width="750"
data-content-height="1624" data-multi-fingered="2" data-show-fps="false" data-show-log="false"
data-show-fps-style="x:0,y:0,size:12,textColor:0xffffff,bgAlpha:0.9">
</div>
<script src="libs/modules/egret/egret.js"></script>
......
{
"groups": [
{
"keys": "bg_jpg,circle_png,jj_jpg,rect_png",
"keys": "desk_png,box_png",
"name": "preload"
}
],
"resources": [
{
"url": "assets/bg.jpg",
"url": "assets/box.png",
"type": "image",
"name": "bg_jpg"
"name": "box_png"
},
{
"name": "circle_png",
"url": "assets/desk.png",
"type": "image",
"url": "assets/circle.png"
},
{
"name": "jj_jpg",
"type": "image",
"url": "assets/jj.jpg"
},
{
"name": "rect_png",
"type": "image",
"url": "assets/rect.png"
"name": "desk_png"
}
]
}
\ No newline at end of file
{
"skins": {
"eui.Button": "resource/eui_skins/ButtonSkin.exml",
"eui.CheckBox": "resource/eui_skins/CheckBoxSkin.exml",
"eui.HScrollBar": "resource/eui_skins/HScrollBarSkin.exml",
"eui.HSlider": "resource/eui_skins/HSliderSkin.exml",
"eui.Panel": "resource/eui_skins/PanelSkin.exml",
"eui.TextInput": "resource/eui_skins/TextInputSkin.exml",
"eui.ProgressBar": "resource/eui_skins/ProgressBarSkin.exml",
"eui.RadioButton": "resource/eui_skins/RadioButtonSkin.exml",
"eui.Scroller": "resource/eui_skins/ScrollerSkin.exml",
"eui.ToggleSwitch": "resource/eui_skins/ToggleSwitchSkin.exml",
"eui.VScrollBar": "resource/eui_skins/VScrollBarSkin.exml",
"eui.VSlider": "resource/eui_skins/VSliderSkin.exml",
"eui.ItemRenderer": "resource/eui_skins/ItemRendererSkin.exml"
},
"autoGenerateExmlsList": true,
"exmls": [
"resource/eui_skins/ButtonSkin.exml",
"resource/eui_skins/CheckBoxSkin.exml",
"resource/eui_skins/HScrollBarSkin.exml",
"resource/eui_skins/HSliderSkin.exml",
"resource/eui_skins/ItemRendererSkin.exml",
"resource/eui_skins/PanelSkin.exml",
"resource/eui_skins/ProgressBarSkin.exml",
"resource/eui_skins/RadioButtonSkin.exml",
"resource/eui_skins/ScrollerSkin.exml",
"resource/eui_skins/TextInputSkin.exml",
"resource/eui_skins/ToggleSwitchSkin.exml",
"resource/eui_skins/VScrollBarSkin.exml",
"resource/eui_skins/VSliderSkin.exml"
],
"path": "resource/default.thm.json"
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8" ?>
<e:Skin class="skins.ButtonSkin" states="up,down,disabled" minHeight="50" minWidth="100" xmlns:e="http://ns.egret.com/eui">
<e:Image width="100%" height="100%" scale9Grid="1,3,8,8" alpha.disabled="0.5"
source="button_up_png"
source.down="button_down_png"/>
<e:Label id="labelDisplay" top="8" bottom="8" left="8" right="8"
size="20"
textColor="0xFFFFFF" verticalAlign="middle" textAlign="center"/>
<e:Image id="iconDisplay" horizontalCenter="0" verticalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.CheckBoxSkin" states="up,down,disabled,upAndSelected,downAndSelected,disabledAndSelected" xmlns:e="http://ns.egret.com/eui">
<e:Group width="100%" height="100%">
<e:layout>
<e:HorizontalLayout verticalAlign="middle"/>
</e:layout>
<e:Image fillMode="scale" alpha="1" alpha.disabled="0.5" alpha.down="0.7"
source="checkbox_unselect_png"
source.upAndSelected="checkbox_select_up_png"
source.downAndSelected="checkbox_select_down_png"
source.disabledAndSelected="checkbox_select_disabled_png"/>
<e:Label id="labelDisplay" size="20" textColor="0x707070"
textAlign="center" verticalAlign="middle"
fontFamily="Tahoma"/>
</e:Group>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.HScrollBarSkin" minWidth="20" minHeight="8" xmlns:e="http://ns.egret.com/eui">
<e:Image id="thumb" source="roundthumb_png" scale9Grid="3,3,2,2" height="8" width="30" verticalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.HSliderSkin" minWidth="20" minHeight="8" xmlns:e="http://ns.egret.com/eui">
<e:Image id="track" source="track_sb_png" scale9Grid="1,1,4,4" width="100%"
height="6" verticalCenter="0"/>
<e:Image id="thumb" source="thumb_png" verticalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8" ?>
<e:Skin class="skins.ItemRendererSkin" states="up,down,disabled" minHeight="50" minWidth="100" xmlns:e="http://ns.egret.com/eui">
<e:Image width="100%" height="100%" scale9Grid="1,3,8,8" alpha.disabled="0.5"
source="button_up_png"
source.down="button_down_png"/>
<e:Label id="labelDisplay" top="8" bottom="8" left="8" right="8"
size="20" fontFamily="Tahoma"
textColor="0xFFFFFF" text="{data}" verticalAlign="middle" textAlign="center"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.PanelSkin" minHeight="230" minWidth="450" xmlns:e="http://ns.egret.com/eui">
<e:Image left="0" right="0" bottom="0" top="0" source="border_png" scale9Grid="2,2,12,12" />
<e:Group id="moveArea" left="0" right="0" top="0" height="45">
<e:Image left="0" right="0" bottom="0" top="0" source="header_png"/>
<e:Label id="titleDisplay" size="20" fontFamily="Tahoma" textColor="0xFFFFFF"
wordWrap="false" left="15" right="5" verticalCenter="0"/>
</e:Group>
<e:Button id="closeButton" label="close" bottom="5" horizontalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.ProgressBarSkin" minWidth="30" minHeight="18" xmlns:e="http://ns.egret.com/eui">
<e:Image source="track_pb_png" scale9Grid="1,1,4,4" width="100%"
height="100%" verticalCenter="0"/>
<e:Image id="thumb" height="100%" width="100%" source="thumb_pb_png"/>
<e:Label id="labelDisplay" textAlign="center" verticalAlign="middle"
size="15" fontFamily="Tahoma" textColor="0x707070"
horizontalCenter="0" verticalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.RadioButtonSkin" states="up,down,disabled,upAndSelected,downAndSelected,disabledAndSelected" xmlns:e="http://ns.egret.com/eui">
<e:Group width="100%" height="100%">
<e:layout>
<e:HorizontalLayout verticalAlign="middle"/>
</e:layout>
<e:Image fillMode="scale" alpha="1" alpha.disabled="0.5" alpha.down="0.7"
source="radiobutton_unselect_png"
source.upAndSelected="radiobutton_select_up_png"
source.downAndSelected="radiobutton_select_down_png"
source.disabledAndSelected="radiobutton_select_disabled_png"/>
<e:Label id="labelDisplay" size="20" textColor="0x707070"
textAlign="center" verticalAlign="middle"
fontFamily="Tahoma"/>
</e:Group>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.ScrollerSkin" minWidth="20" minHeight="20" xmlns:e="http://ns.egret.com/eui">
<e:HScrollBar id="horizontalScrollBar" width="100%" bottom="0"/>
<e:VScrollBar id="verticalScrollBar" height="100%" right="0"/>
</e:Skin>
\ No newline at end of file
<?xml version='1.0' encoding='utf-8'?>
<e:Skin class="skins.TextInputSkin" minHeight="40" minWidth="300" states="normal,disabled,normalWithPrompt,disabledWithPrompt" xmlns:e="http://ns.egret.com/eui">
<e:Image width="100%" height="100%" scale9Grid="1,3,8,8" source="button_up_png"/>
<e:Rect height="100%" width="100%" fillColor="0xffffff"/>
<e:EditableText id="textDisplay" verticalCenter="0" left="10" right="10"
textColor="0x000000" textColor.disabled="0xff0000" width="100%" height="24" size="20" />
<e:Label id="promptDisplay" verticalCenter="0" left="10" right="10"
textColor="0xa9a9a9" width="100%" height="24" size="20" touchEnabled="false" includeIn="normalWithPrompt,disabledWithPrompt"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.ToggleSwitchSkin" states="up,down,disabled,upAndSelected,downAndSelected,disabledAndSelected" xmlns:e="http://ns.egret.com/eui">
<e:Image source="on_png"
source.up="off_png"
source.down="off_png"
source.disabled="off_png"/>
<e:Image source="handle_png"
horizontalCenter="-18"
horizontalCenter.upAndSelected="18"
horizontalCenter.downAndSelected="18"
horizontalCenter.disabledAndSelected="18"
verticalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.VScrollBarSkin" minWidth="8" minHeight="20" xmlns:e="http://ns.egret.com/eui">
<e:Image id="thumb" source="roundthumb_png" scale9Grid="3,3,2,2" height="30" width="8" horizontalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.VSliderSkin" minWidth="25" minHeight="30" xmlns:e="http://ns.egret.com/eui">
<e:Image id="track" source="track_png" scale9Grid="1,1,4,4" width="7" height="100%" horizontalCenter="0"/>
<e:Image id="thumb" source="thumb_png" horizontalCenter="0" />
</e:Skin>
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-present, Egret Technology.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
export default class AssetAdapter implements eui.IAssetAdapter {
/**
* @language zh_CN
* 解析素材
* @param source 待解析的新素材标识符
* @param compFunc 解析完成回调函数,示例:callBack(content:any,source:string):void;
* @param thisObject callBack的 this 引用
*/
public getAsset(source: string, compFunc:Function, thisObject: any): void {
function onGetRes(data: any): void {
compFunc.call(thisObject, data, source);
}
if (RES.hasRes(source)) {
let data = RES.getRes(source);
if (data) {
onGetRes(data);
}
else {
RES.getResAsync(source, onGetRes, this);
}
}
else {
RES.getResByUrl(source, onGetRes, this, RES.ResourceItem.TYPE_IMAGE);
}
}
}
import AssetAdapter from "./AssetAdapter";
import ThemeAdapter from "./ThemeAdapter";
import { getResPath } from "./utils";
import { SimpleP2APP } from "./section1/SimpleP2APP";
import { SimpleP2APPWithDebugDraw } from "./section1/SimpleP2APPWithDebugDraw";
import TestAsset from "./section2/TestAsset";
class Main extends eui.UILayer {
/**
* 创建场景界面
* Create scene interface
*/
protected createGameScene(): void {
let img: egret.Bitmap = new egret.Bitmap();
img = this.createBitmapByName("bg_jpg");
img.width = this.stage.stageWidth;
img.height = this.stage.stageHeight;
this.addChild(img);
this.CreateWorld();
this.CreatePlane();
this.addEventListener(egret.Event.ENTER_FRAME, this.update, this);
this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onButtonClick, this);
}
//使用P2物理引擎创建物理应用的过程大致分为5个步骤:
// 1创建world世界
// 2创建shape形状
// 3创建body刚体
// 4实时调用step()函数,更新物理模拟计算
// 5基于形状、刚体,使用Egret渲染,显示物理模拟效果
//创建Word世界
private world: p2.World;
private CreateWorld() {
this.world = new p2.World();
//设置world为睡眠状态
this.world.sleepMode = p2.World.BODY_SLEEPING;
// gravity=[x,y] x为水平方向重力,正数表示方向向右。y为垂直方向重力,正数表示方向向下。
this.world.gravity = [0, 10];
// this.world.gravity = [0, 10];
}
//生成地板Plane
private planeBody: p2.Body;
private CreatePlane() {
let planeShape: p2.Plane = new p2.Plane();
this.planeBody = new p2.Body({
type: p2.Body.STATIC, //刚体类型
position: [0, this.stage.stageHeight], //刚体的位置
});
this.planeBody.angle = Math.PI;//Plane相当于地面,默认面向Y轴方向。将地面翻转180度
this.planeBody.displays = [];
this.planeBody.addShape(planeShape);
this.world.addBody(this.planeBody);
}
private shpeBody: p2.Body;
//贴图显示对象
private display: egret.DisplayObject;
private onButtonClick(e: egret.TouchEvent) {
if (Math.random() > 0.5) {
//添加方形刚体
var boxShape = new p2.Box({ width: 140, height: 80 });
this.shpeBody = new p2.Body({
mass: 1,
position: [e.stageX, e.stageY],
angularVelocity: 1//下落时旋转的速度
});
this.shpeBody.addShape(boxShape);
this.world.addBody(this.shpeBody);
this.display = this.createBitmapByName("rect_png");
this.display.width = boxShape.width;
this.display.height = boxShape.height;
console.log(e.stageX, e.stageY);
}
else {
//添加圆形刚体
var circleShape = new p2.Circle({ radius: 60 });
this.shpeBody = new p2.Body({ mass: 0.1, position: [e.stageX, e.stageY] });
this.shpeBody.addShape(circleShape);
this.world.addBody(this.shpeBody);
this.display = this.createBitmapByName("circle_png");
this.display.width = circleShape.radius * 2
this.display.height = circleShape.radius * 2
}
//Egret中加载进来的图像,其原点默认为左上角,而P2中刚体的原点处于其中心位置,如下图(盗了一张图)
this.display.anchorOffsetX = this.display.width / 2
this.display.anchorOffsetY = this.display.height / 2;
this.display.x = -100;
this.display.y = -100;
this.display.rotation = 270
this.shpeBody.displays = [this.display];
this.addChild(this.display);
}
//帧事件,步函数
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) {
box.x = boxBody.position[0];
box.y = boxBody.position[1];
//这里刷新图片旋转
box.rotation = boxBody.angle * 180 / Math.PI;
if (boxBody.sleepState == p2.Body.SLEEPING) {
box.alpha = 0.5;
}
else {
box.alpha = 1;
}
}
}
}
/**
* 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
*/
private createBitmapByName(name: string): egret.Bitmap {
var result: egret.Bitmap = new egret.Bitmap();
var texture: egret.Texture = RES.getRes(name);
result.texture = texture;
return result;
}
protected createChildren(): void {
super.createChildren();
egret.lifecycle.addLifecycleListener((context) => {
// custom lifecycle plugin
})
egret.lifecycle.onPause = () => {
egret.ticker.pause();
}
egret.lifecycle.onResume = () => {
egret.ticker.resume();
}
//inject the custom material parser
//注入自定义的素材解析器
let assetAdapter = new AssetAdapter();
egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());
this.runGame().catch(e => {
console.log(e);
})
}
private async runGame() {
await this.loadResource()
this.createGameScene();
const result = await RES.getResAsync("description_json")
await platform.login();
const userInfo = await platform.getUserInfo();
console.log(userInfo);
}
private async loadResource() {
try {
// const loadingView = new LoadingUI();
// this.stage.addChild(loadingView);
await RES.loadConfig("default.res.json", getResPath() + "resource/");
await this.loadTheme();
await RES.loadGroup("preload", 0);
}
catch (e) {
console.error(e);
}
}
private loadTheme() {
return new Promise((resolve, reject) => {
// load skin theme configuration file, you can manually modify the file. And replace the default skin.
//加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
let theme = new eui.Theme("resource/default.thm.json", this.stage);
theme.addEventListener(eui.UIEvent.COMPLETE, () => {
resolve();
}, this);
})
}
}
window['Main'] = Main;
\ No newline at end of file
SimpleP2APP;
SimpleP2APPWithDebugDraw;
TestAsset
\ No newline at end of file
/**
* 平台数据接口。
* 由于每款游戏通常需要发布到多个平台上,所以提取出一个统一的接口用于开发者获取平台数据信息
* 推荐开发者通过这种方式封装平台逻辑,以保证整体结构的稳定
* 由于不同平台的接口形式各有不同,白鹭推荐开发者将所有接口封装为基于 Promise 的异步形式
*/
declare interface Platform {
getUserInfo(): Promise<any>;
login(): Promise<any>
}
class DebugPlatform implements Platform {
async getUserInfo() {
return { nickName: "username" }
}
async login() {
}
}
if (!window.platform) {
window.platform = new DebugPlatform();
}
declare let platform: Platform;
declare interface Window {
platform: Platform
}
import { getResPath } from "./utils";
export class StarterBase extends eui.UILayer {
public factor: number = 30;
protected createGameScene(): void {
//添加游戏帧频事件
this.addEventListener(egret.Event.ENTER_FRAME, this.loop, this);
}
protected createChildren(): void {
super.createChildren();
this.runGame().catch(e => {
console.log(e);
})
}
loop() {
}
private async runGame() {
await this.loadResource()
this.createGameScene();
}
private async loadResource() {
try {
await RES.loadConfig("default.res.json", getResPath() + "resource/");
await RES.loadGroup("preload", 0);
}
catch (e) {
console.error(e);
}
}
}
\ No newline at end of file
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-present, Egret Technology.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
export default class ThemeAdapter implements eui.IThemeAdapter {
/**
* 解析主题
* @param url 待解析的主题url
* @param onSuccess 解析完成回调函数,示例:compFunc(e:egret.Event):void;
* @param onError 解析失败回调函数,示例:errorFunc():void;
* @param thisObject 回调的this引用
*/
public getTheme(url: string, onSuccess: Function, onError: Function, thisObject: any): void {
function onResGet(e: string): void {
onSuccess.call(thisObject, e);
}
function onResError(e: RES.ResourceEvent): void {
if (e.resItem.url == url) {
RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, onResError, null);
onError.call(thisObject);
}
}
if (typeof generateEUI !== 'undefined') {
egret.callLater(() => {
onSuccess.call(thisObject, generateEUI);
}, this);
}
else if (typeof generateEUI2 !== 'undefined') {
RES.getResByUrl("resource/gameEui.json", (data, url) => {
window["JSONParseClass"]["setData"](data);
egret.callLater(() => {
onSuccess.call(thisObject, generateEUI2);
}, this);
}, this, RES.ResourceItem.TYPE_JSON);
}
else {
RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, onResError, null);
RES.getResByUrl(url, onResGet, this, RES.ResourceItem.TYPE_TEXT);
}
}
}
declare var generateEUI: { paths: string[], skins: any }
declare var generateEUI2: { paths: string[], skins: any }
\ No newline at end of file
export default class p2DebugDraw{
private sprite: egret.Sprite;
private world: p2.World;
private COLOR_D_SLEEP: number = 0x999999;
private COLOR_D_WAKE: number = 0xe5b2b2;
private COLOR_K: number = 0x7f7fe5;
private COLOR_S: number = 0x7fe57f;
private COLOR_BLACK: number = 0x000000;
private COLOR_RED: number = 0xff0000;
public isDrawAABB: boolean = false;
public factor:number = 30;
public constructor(world: p2.World,sprite:egret.Sprite) {
this.world = world;
this.sprite = sprite;
}
public drawDebug(): void {
this.sprite.graphics.clear();
var l: number = this.world.bodies.length;
for (var i: number = 0; i < l; i++) {
var body: p2.Body = this.world.bodies[i];
for (var j: number = 0; j < body.shapes.length; j++) {
var shape: p2.Shape = body.shapes[j];
this.drawShape(shape, body);
if (this.isDrawAABB) this.drawAABB(body);
}
}
l = this.world.constraints.length;
var jointType: number, joint: p2.Constraint;
for (var j: number = 0; j < l; j++) {
joint = this.world.constraints[j];
switch (joint.type) {
case p2.Constraint.DISTANCE:
this.drawDistanceJoint(<p2.DistanceConstraint>joint);
break;
case p2.Constraint.REVOLUTE:
this.drawRevoluteJoint(<p2.RevoluteConstraint>joint);
break;
case p2.Constraint.GEAR:
this.drawGearJoint(<p2.GearConstraint>joint);
break;
case p2.Constraint.PRISMATIC:
this.drawPrismaticJoint(<p2.PrismaticConstraint>joint);
break;
case p2.Constraint.LOCK:
this.drawLockJoint(<p2.LockConstraint>joint);
break;
}
}
l = this.world.springs.length;
var springType: number, spring: p2.Spring;
for (var s: number = 0; s < l; s++) {
spring = this.world.springs[s];
if (spring instanceof p2.LinearSpring) {
this.drawLinearSpring(<p2.LinearSpring>spring);
} else if (spring instanceof p2.RotationalSpring) {
this.drawRotationalSpring(<p2.RotationalSpring>spring);
}
}
}
private drawAABB(body: p2.Body): void {
var vertices: number[][] = new Array();
var lx: number = body.aabb.lowerBound[0];
var ly: number = body.aabb.lowerBound[1];
var ux: number = body.aabb.upperBound[0];
var uy: number = body.aabb.upperBound[1];
if (isFinite(lx) && isFinite(ly) && isFinite(ux) && isFinite(uy)) {
vertices.push([lx, ly], [ux, ly], [ux, uy], [lx, uy]);
this.drawConvex(vertices, this.COLOR_S,1,false);
}
}
private drawDistanceJoint(joint: p2.DistanceConstraint): void {
var pA: number[] = new Array(), pB: number[] = new Array(), distance: number;
distance = joint.distance;
if (joint.upperLimitEnabled && joint.upperLimit > distance) distance = joint.upperLimit;
joint.bodyA.toWorldFrame(pA, joint.localAnchorA);
joint.bodyB.toWorldFrame(pB, joint.localAnchorB);
var segment: number[] = p2.vec2.subtract([], pB, pA);
p2.vec2.normalize(segment, segment);
p2.vec2.scale(segment, segment, distance);
var anchorB: number[] = p2.vec2.add([], pA, segment);
this.drawSegment(pA, joint.bodyA.position, this.COLOR_S);
this.drawSegment(pB, joint.bodyB.position, this.COLOR_S);
this.drawVecAt(segment, pA, this.COLOR_BLACK);
//draw maxfore
if(joint.position>distance) this.drawSegment(pB, anchorB, this.COLOR_RED);
//draw anchorA
this.drawCircle(pA, 3/this.factor, this.COLOR_BLACK);
//draw upperlimit, which is also anchorB
this.drawCircle(anchorB, 3/this.factor, this.COLOR_BLACK);
//draw lowerlimit
if (joint.lowerLimitEnabled) {
p2.vec2.normalize(segment, segment);
p2.vec2.scale(segment, segment, joint.lowerLimit);
anchorB = p2.vec2.add([], pA, segment);
this.drawCircle(anchorB, 2/this.factor, this.COLOR_BLACK);
}
}
private drawRevoluteJoint(joint: p2.RevoluteConstraint): void {
var anchorA: number[] = new Array(), anchorB: number[] = new Array();
joint.bodyA.toWorldFrame(anchorA, joint.pivotA);
joint.bodyB.toWorldFrame(anchorB, joint.pivotB);
this.drawSegment(joint.bodyA.position, anchorA, this.COLOR_S);
this.drawSegment(joint.bodyB.position, anchorB, this.COLOR_S);
this.drawSegment(anchorA, anchorB, this.COLOR_RED);
this.drawCircle(anchorA, 3/this.factor, this.COLOR_BLACK);
}
private drawGearJoint(joint: p2.GearConstraint): void {
var pA: number[] = joint.bodyA.position;
var pB: number[] = joint.bodyB.position;
var pA1: number[] = new Array(), pB1: number[] = new Array();
joint.bodyA.toWorldFrame(pA1, [20/this.factor, 0]);
joint.bodyB.toWorldFrame(pB1, [20/this.factor, 0]);
var v1: number[] = p2.vec2.subtract([], pA, pA1);
var v2: number[] = p2.vec2.subtract([], pB, pB1);
this.drawVecAt(v1, pA, this.COLOR_BLACK, true);
this.drawVecAt(v2, pB, this.COLOR_BLACK, true);
joint.bodyB.toWorldFrame(v2, [10 * (joint.bodyB.angle - joint.bodyA.angle - joint.angle)/this.factor, 0]);
this.drawSegment(v2, pB, this.COLOR_RED);
}
private drawPrismaticJoint(joint: p2.PrismaticConstraint): void {
var pA: number[] = joint.bodyA.position;
var pB: number[] = joint.bodyB.position;
var anchorA: number[] = new Array(), anchorB: number[] = new Array();
joint.bodyA.toWorldFrame(anchorA, joint.localAnchorA);
joint.bodyB.toWorldFrame(anchorB, joint.localAnchorB);
var axis: number[] = new Array()
axis = this.toWorldVector(joint.localAxisA, joint.bodyA);
var lowerAxis: number[] = p2.vec2.copy([], axis);
var upperAxis: number[] = p2.vec2.copy([], axis);
if (joint.lowerLimitEnabled) {
p2.vec2.scale(lowerAxis, axis, joint.lowerLimit);
} else {
p2.vec2.scale(lowerAxis, axis, 5000);
}
if (joint.upperLimitEnabled) {
p2.vec2.scale(upperAxis, axis, joint.upperLimit);
} else {
p2.vec2.scale(upperAxis, axis, 5000);
}
this.drawVecAt(lowerAxis, anchorA, this.COLOR_BLACK, true);
this.drawVecAt(upperAxis, anchorA, this.COLOR_BLACK, true);
p2.vec2.add(lowerAxis, lowerAxis, anchorA);
this.drawCircle(lowerAxis, 2/this.factor, this.COLOR_BLACK, 1, true);
p2.vec2.add(upperAxis, upperAxis, anchorA);
this.drawCircle(upperAxis, 2/this.factor, this.COLOR_BLACK, 1, true);
}
private drawLockJoint(joint: p2.LockConstraint): void {
var offset: number[] = new Array(), pB: number[] = new Array();
joint.bodyA.toWorldFrame(offset, joint.localOffsetB);
this.drawSegment(offset, joint.bodyA.position, this.COLOR_S);
this.drawSegment(offset, joint.bodyB.position, this.COLOR_RED);
this.drawCircle(offset, 3/this.factor, this.COLOR_BLACK);
var angleIndicator:number[] = new Array();
joint.bodyA.toWorldFrame(angleIndicator, [20/this.factor, 0]);
this.drawSegment(angleIndicator, joint.bodyA.position, this.COLOR_BLACK);
joint.bodyB.toWorldFrame(angleIndicator, [20/this.factor, 0]);
this.drawSegment(angleIndicator, joint.bodyB.position, this.COLOR_BLACK);
}
private drawLinearSpring(spring: p2.LinearSpring): void {
var pA: number[] = new Array(), pB: number[] = new Array();
spring.bodyA.toWorldFrame(pA, spring.localAnchorA);
spring.bodyB.toWorldFrame(pB, spring.localAnchorB);
var segment: number[] = p2.vec2.subtract([], pB, pA);
p2.vec2.normalize(segment, segment);
p2.vec2.scale(segment, segment, spring.restLength);
var anchorB: number[] = p2.vec2.add([], spring.bodyA.position, segment);
this.drawSegment(anchorB, spring.bodyB.position, this.COLOR_RED);
this.drawVecAt(segment, pA, this.COLOR_BLACK);
this.drawCircle(pA, 3/this.factor, this.COLOR_RED);
this.drawCircle(anchorB, 3/this.factor, this.COLOR_RED);
}
private drawRotationalSpring(spring: p2.RotationalSpring): void {
var pA: number[] = new Array(), pB: number[] = new Array();
pA = spring.bodyA.position;
pB = spring.bodyB.position;
var pA1: number[] = new Array(), pB1: number[] = new Array();
spring.bodyA.toWorldFrame(pA1, [20/this.factor, 0]);
spring.bodyB.toWorldFrame(pB1, [10 * (spring.bodyB.angle - spring.bodyA.angle - spring.restAngle + 2)/this.factor, 0]);
var v1: number[] = p2.vec2.subtract([], pA1, pA);
var v2: number[] = p2.vec2.subtract([], pB1, pB);
this.drawVecAt(v1, pA, this.COLOR_RED, true);
this.drawVecAt(v2, pB, this.COLOR_RED, true);
spring.bodyB.toWorldFrame(pB1, [20/this.factor, 0]);
this.drawCircle(pA1, 2/this.factor, this.COLOR_RED);
this.drawCircle(pB1, 2/this.factor, this.COLOR_RED);
}
public drawShape(shape: p2.Shape, body: p2.Body, color?: number, fillColor?: boolean): void {
var color: number = color==undefined ?this.getColor(body):color;
var fillColor: boolean = fillColor==undefined ? true:fillColor;
if (shape instanceof p2.Convex) {
this.drawConvexShape(<p2.Convex>shape, body, color, fillColor);
}
else if (shape instanceof p2.Plane) {
this.drawPlaneShape(<p2.Plane>shape, body, color, fillColor);
}
else if (shape instanceof p2.Circle) {
this.drawCircleShape(<p2.Circle>shape, body, color, fillColor);
}
else if (shape instanceof p2.Capsule) {
this.drawCapsule(<p2.Capsule>shape, body,color);
}
else if (shape instanceof p2.Particle) {
this.drawParticle(<p2.Particle>shape, body,color);
}
else if (shape instanceof p2.Line) {
this.drawLine(<p2.Line>shape, body,color);
}
else if (shape instanceof p2.Heightfield) {
this.drawHeightfeild(<p2.Heightfield>shape, body,color);
}
}
private drawConvexShape(shape: p2.Convex, b: p2.Body, color: number,fillColor:boolean): void {
var indexofShape: number = b.shapes.indexOf(shape);
var offset: number[] = shape.position;
var angle: number = shape.angle;
var shapeCenter: number[] = [];
var worldPoint: number[] = this.transformVec(shape.vertices[0], offset, angle);
b.toWorldFrame(shapeCenter, offset);
b.toWorldFrame(worldPoint, worldPoint);
this.drawSegment(shapeCenter, worldPoint, color);
var worldVertices: number[][] = new Array();
var l: number = shape.vertices.length;
for (var i: number = 0; i < l; i++) {
worldPoint = this.transformVec(shape.vertices[i], offset, angle);
b.toWorldFrame(worldPoint, worldPoint);
worldVertices.push(worldPoint);
}
//console.log(worldVertices[0]);
this.drawConvex(worldVertices, color, 0.5, fillColor);
}
private drawParticle(shape: p2.Particle, b: p2.Body, color: number): void {
this.drawCircle(b.position, 1/this.factor, color, 0.5);
this.drawCircle(b.position, 5/this.factor, color, 1,false);
}
private drawLine(shape: p2.Line, b: p2.Body,color:number): void {
var len: number = shape.length;
var p1: number[] = new Array(), p2: number[] = new Array();
b.toWorldFrame(p1, [-len / 2, 0]);
b.toWorldFrame(p2, [len / 2, 0]);
this.drawSegment(p1, p2, color);
}
private drawHeightfeild(shape: p2.Heightfield, b: p2.Body,color:number): void {
var g: egret.Graphics = this.sprite.graphics;
g.lineStyle(1, color);
g.beginFill(color, 0.5);
var data: number[] = shape.heights;
var elementWidth: number = shape.elementWidth;
var x: number;
var worldPoint: number[] = new Array();
var worldVertices: number[][] = new Array();
data.forEach(function (y: number, i: number) {
x = i * elementWidth;
worldPoint = new Array();
b.toWorldFrame(worldPoint, [x, y]);
worldVertices.push(worldPoint);
});
worldPoint = new Array();
b.toWorldFrame(worldPoint, [x, -500]);
worldVertices.push(worldPoint);
worldPoint = new Array();
b.toWorldFrame(worldPoint, [0, -500]);
worldVertices.push(worldPoint);
worldPoint = new Array();
b.toWorldFrame(worldPoint, [0, 0]);
worldVertices.push(worldPoint);
this.drawConvex(worldVertices, color, 0.5);
}
private drawCapsule(shape: p2.Capsule, b: p2.Body,color:number): void {
var len: number = shape.length;
var radius: number = shape.radius;
var p1: number[] = new Array(), p2: number[] = new Array(), p3: number[] = new Array(), p4: number[] = new Array();
var a1: number[] = new Array(), a2: number[] = new Array();
b.toWorldFrame(p1, [-len / 2, -radius]);
b.toWorldFrame(p2, [len / 2, -radius]);
b.toWorldFrame(p3, [len / 2, radius]);
b.toWorldFrame(p4, [-len / 2, radius]);
b.toWorldFrame(a1, [len / 2, 0]);
b.toWorldFrame(a2, [-len / 2, 0]);
this.drawCircle(a1, radius, color, 0.5);
this.drawCircle(a2, radius, color, 0.5);
this.drawConvex([p1,p2,p3,p4], color, 0.5);
}
private drawCircleShape(shape: p2.Circle, b: p2.Body, color?:number,solid?:boolean): void {
var offset: number[] = shape.position;
var angle: number = shape.angle;
var pos: number[] = new Array();
b.toWorldFrame(pos, offset);
this.drawCircle(pos, shape.radius, color, 0.5,solid);
var edge: number[] = this.transformVec([shape.radius, 0], offset, angle);
b.toWorldFrame(edge, edge);
this.drawSegment(pos, edge, color);
}
private drawPlaneShape(shape: p2.Plane, b: p2.Body,color:number,fillColor:boolean): void {
var worldPoint: number[] = new Array();
var worldVertices: number[][] = new Array();
var i: number = b.shapes.indexOf(shape);
b.toWorldFrame(worldPoint, [1000, 0]);
worldPoint = this.transformVec(worldPoint, shape.position, shape.angle);
worldVertices.push(worldPoint);
worldPoint = new Array();
b.toWorldFrame(worldPoint, [1000, -100000]);
worldPoint = this.transformVec(worldPoint, shape.position, shape.angle);
worldVertices.push(worldPoint);
worldPoint = new Array();
b.toWorldFrame(worldPoint, [-1000, -100000]);
worldPoint = this.transformVec(worldPoint, shape.position, shape.angle);
worldVertices.push(worldPoint);
worldPoint = new Array();
b.toWorldFrame(worldPoint, [-1000, 0]);
worldPoint = this.transformVec(worldPoint, shape.position, shape.angle);
worldVertices.push(worldPoint);
this.drawConvex(worldVertices, color, 0.5, fillColor);
}
private getColor(b: p2.Body): number {
var color: number = this.COLOR_D_SLEEP;
if (b.type == p2.Body.KINEMATIC) {
color = this.COLOR_K;
} else if (b.type == p2.Body.STATIC) {
color = this.COLOR_S;
} else if (b.sleepState == p2.Body.AWAKE) {
color = this.COLOR_D_WAKE;
}
return color;
}
public drawVecAt(v: number[], at: number[], color: number, markStart: boolean = false): void {
var pa: number[] = p2.vec2.copy([], at);
var pb: number[] = p2.vec2.add([], v, at);
if (markStart) this.drawCircle(pa, 3/this.factor, color);
this.drawSegment(pa, pb, color);
}
public drawVecTo(v: number[], to: number[], color: number, markStart: boolean = false): void {
var pa: number[] = p2.vec2.copy([], to);
var pb: number[] = p2.vec2.subtract([], to, v);
if (markStart) this.drawCircle(pa, 3/this.factor, color);
this.drawSegment(pa, pb, color);
}
public drawSegment(start: number[], end: number[], color: number): void {
this.sprite.graphics.lineStyle(1, color);
this.sprite.graphics.moveTo(start[0]*this.factor, start[1]*this.factor);
this.sprite.graphics.lineTo(end[0]*this.factor, end[1]*this.factor);
}
public drawCircle(pos: number[], radius: number, color: number, alpha: number= 1,fillColor?:boolean): void {
this.sprite.graphics.lineStyle(1, color);
if (fillColor || fillColor==undefined) this.sprite.graphics.beginFill(color, alpha);
this.sprite.graphics.drawCircle(pos[0]*this.factor, pos[1]*this.factor, radius*this.factor);
this.sprite.graphics.endFill();
}
public drawConvex(vertices: number[][], color: number, alpha: number= 1,fillColor:boolean=true): void {
this.sprite.graphics.lineStyle(1, color);
if(fillColor) this.sprite.graphics.beginFill(color, alpha);
var l: number = vertices.length;
var worldPoint: number[] = vertices[0];
this.sprite.graphics.moveTo(worldPoint[0]*this.factor, worldPoint[1]*this.factor);
for (var i: number = 1; i <= l; i++) {
worldPoint = vertices[i % l];
this.sprite.graphics.lineTo(worldPoint[0]*this.factor, worldPoint[1]*this.factor);
}
this.sprite.graphics.endFill();
}
public toWorldVector(v: number[], b: p2.Body): number[]{
var out: number[] = new Array();
p2.vec2.rotate(out, v, b.angle);
return out;
}
public transformVec(v: number[], offset: number[], angle: number): number[]{
var nv: number[] = new Array();
p2.vec2.rotate(nv, v, angle);
p2.vec2.add(nv, nv, offset);
return nv;
}
public drawDotLine(vertices: number[][], color: number=0, smoothly: boolean= false, segmentLength: number= 30): void {
if (vertices.length < 2) return;
var dotSize: number = 2 / this.factor;
var firstPoint: number[] = [];
p2.vec2.copy(firstPoint,vertices[0]);
this.drawCircle(firstPoint, dotSize, color, 1, false);
for (var i: number = 0; i < vertices.length-2; i++) {
var p: number[] = vertices[i];
if (smoothly) {
var distance: number = p2.vec2.distance(firstPoint,p);
while (distance > (segmentLength / this.factor)) {
var distanceVector: number[] = [];
p2.vec2.subtract(distanceVector, p, firstPoint);
p2.vec2.scale(distanceVector, distanceVector, segmentLength / this.factor / distance);
p2.vec2.add(firstPoint, firstPoint, distanceVector);
this.drawCircle(firstPoint, dotSize, color, 1, false);
distance = p2.vec2.distance(firstPoint, p);
}
} else {
this.drawCircle(p, dotSize, color,1,false);
}
}
}
}
import { StarterBase } from "../StarterBase";
export class SimpleP2APP extends StarterBase {
private world: p2.World;
private body: p2.Body;
public createP2App(): void {
//创建p2物理世界world
this.world = new p2.World();
var world = this.world;
world.gravity = [10, 10];
//创建矩形形状shape
var shape: p2.Box = new p2.Box({ width: 100 / this.factor, height: 50 / this.factor });
//创建刚体body
var body: p2.Body = new p2.Body({ mass: 1 });
body.position = [275 / this.factor, 100 / this.factor];
body.addShape(shape);
world.addBody(body);
this.body = body;
}
loop(): void {
this.world.step(1 / 60);
console.log(this.body.position);
}
protected createGameScene(): void {
super.createGameScene();
this.createP2App();
}
}
window['SimpleP2APP'] = SimpleP2APP;
\ No newline at end of file
import { StarterBase } from "../StarterBase";
import p2DebugDraw from "../p2DebugDraw";
export class SimpleP2APPWithDebugDraw extends StarterBase {
private world: p2.World;
private debugDraw: p2DebugDraw;
public createP2App(): void {
//创建p2物理世界world
this.world = new p2.World();
var world = this.world;
world.gravity = [0, 10];
//创建矩形形状shape
var shape: p2.Box = new p2.Box({ width: 100 / this.factor, height: 50 / this.factor });
//创建刚体body
var body: p2.Body = new p2.Body({ mass: 1 });
body.position = [275 / this.factor, 100 / this.factor];
body.addShape(shape);
world.addBody(body);
//添加p2调试试图
var sprite: egret.Sprite = new egret.Sprite();
this.addChild(sprite);
this.debugDraw = new p2DebugDraw(world, sprite);
//添加游戏帧频事件
this.addEventListener(egret.Event.ENTER_FRAME, this.loop, this);
}
loop(): void {
this.world.step(1 / 60);
this.debugDraw.drawDebug();
}
protected createGameScene(): void {
super.createGameScene();
this.createP2App();
}
}
window['SimpleP2APPWithDebugDraw'] = SimpleP2APPWithDebugDraw;
\ No newline at end of file
import { StarterBase } from "../StarterBase";
import p2DebugDraw from "../p2DebugDraw";
export default class TestAsset extends StarterBase {
createGameScene() {
super.createGameScene();
this.createWorld();
this.createGround();
this.createBodies();
this.createDebug();
}
private createBodies(): void {
this.createBox(100, 200);
this.createDesk(300, 100);
}
private createBox(x: number, y: number): void {
x = x / this.factor;
y = y / this.factor;
var boxShape: p2.Box = new p2.Box({ width: 60 / this.factor, height: 60 / this.factor });
var boxBody: p2.Body = new p2.Body({ mass: 1, position: [x, y] });
boxBody.addShape(boxShape);
this.world.addBody(boxBody);
this.bindAsset(boxBody, "box_png");
}
private createDesk(x: number, y: number): void {
var _this = this;
x = x / this.factor;
y = y / this.factor;
var deskVertices: number[][] = new Array(
[0, 0],
[0, 16],
[16, 16],
[16, 46],
[32, 46],
[32, 16],
[178, 16],
[178, 46],
[194, 46],
[194, 16],
[210, 16],
[210, 0]
);
deskVertices.forEach(function (vertice: number[]) {
vertice[0] = vertice[0] / _this.factor;
vertice[1] = vertice[1] / _this.factor;
});
var deskBody: p2.Body = new p2.Body({ mass: 1, position: [x, y] });
deskBody.fromPolygon(deskVertices);
this.world.addBody(deskBody);
this.bindAsset(deskBody, "desk_png");
}
private bindAsset(body: p2.Body, assetName: string): void {
var offset: number[] = [];
body.updateAABB();
var bodyWidth: number = body.aabb.upperBound[0] - body.aabb.lowerBound[0];
var bodyHeight: number = body.aabb.upperBound[1] - body.aabb.lowerBound[1];
var asset: egret.Bitmap = new egret.Bitmap();
asset.texture = RES.getRes(assetName);
asset.scaleX = bodyWidth / asset.width * this.factor;
asset.scaleY = bodyHeight / asset.height * this.factor;
this.addChild(asset);
p2.vec2.subtract(offset, body.position, body.aabb.lowerBound);
asset.anchorOffsetX = offset[0] / asset.scaleX * this.factor;
asset.anchorOffsetY = offset[1] / asset.scaleY * this.factor;
body['userData'] = asset;
}
private world: p2.World;
private createWorld(): void {
var wrd: p2.World = new p2.World();
wrd.sleepMode = p2.World.BODY_SLEEPING;
wrd.gravity = [0, 10];
this.world = wrd;
}
//生成地板Plane
private planeBody: p2.Body;
private createGround(): void {
var stageHeight: number = this.stage.stageHeight;
var groundShape: p2.Plane = new p2.Plane();
var groundBody: p2.Body = new p2.Body();
groundBody.position[1] = 1600 / this.factor;
groundBody.angle = Math.PI;
groundBody.addShape(groundShape);
this.world.addBody(groundBody);
// let planeShape: p2.Plane = new p2.Plane();
// this.planeBody = new p2.Body({
// type: p2.Body.STATIC, //刚体类型
// position: [0, this.stage.stageHeight], //刚体的位置
// });
// this.planeBody.angle = Math.PI;//Plane相当于地面,默认面向Y轴方向。将地面翻转180度
// this.planeBody.displays = [];
// this.planeBody.addShape(planeShape);
// this.world.addBody(this.planeBody);
}
loop(): void {
this.world.step(1 / 60);
// this.debugDraw.drawDebug();
var _this = this;
this.world.step(1 / 60);
this.world.bodies.forEach(function (b: p2.Body) {
if (b['userData'] != null) {
b['userData'].x = b.position[0] * _this.factor;
b['userData'].y = b.position[1] * _this.factor;
b['userData'].rotation = b.angle * 180 / Math.PI;
}
});
}
private debugDraw: p2DebugDraw;
private createDebug(): void {
var sprite: egret.Sprite = new egret.Sprite();
this.addChild(sprite);
this.debugDraw = new p2DebugDraw(this.world, sprite);
}
}
window['TestAsset'] = TestAsset;
\ No newline at end of file
export const getResPath = () => window['resPath'] || '';
export const getSkinPath = (key)=>`resource/skins/${key}Skin.exml`
\ No newline at end of file
export const getResPath = () => window['resPath'] || '';
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment