Laya1.0Matter.js案例之牛顿摆

添加物理引擎,往index.html中添加

<script type="text/javascript" src="libs/matter.js"></script>
    <script type="text/javascript" src="libs/LayaRender.js"></script>

如下图所示

 牛顿摆ts源码

module laya {
	import Sprite = Laya.Sprite;
	import Stage = Laya.Stage;
	import Browser = Laya.Browser;
	import WebGL = Laya.WebGL;
	import Render = Laya.Render;

	export class Physics_NewtonsCradle {
		private stageWidth: number = 800;
		private stageHeight: number = 600;

		private Matter: any = Browser.window.Matter;
		private LayaRender: any = Browser.window.LayaRender;

		private mouseConstraint: any;
		private engine: any;

		constructor() {
			// 不支持WebGL时自动切换至Canvas
			Laya.init(this.stageWidth, this.stageHeight, WebGL);

			Laya.stage.alignV = Stage.ALIGN_MIDDLE;
			Laya.stage.alignH = Stage.ALIGN_CENTER;

			Laya.stage.scaleMode = "showall";
			Laya.stage.bgColor = "#232628";

			this.setup();
		}

		private setup(): void {
			this.initMatter();
			this.initWorld();

			Laya.stage.on("resize", this, this.onResize);
		}

		private initMatter(): void {
			var gameWorld: Sprite = new Sprite();
			Laya.stage.addChild(gameWorld);

			// 初始化物理引擎
			this.engine = this.Matter.Engine.create({ enableSleeping: true });
			this.Matter.Engine.run(this.engine);

			var render = this.LayaRender.create({ engine: this.engine, container: gameWorld, width: this.stageWidth, height: this.stageHeight, options: { wireframes: false } });
			this.LayaRender.run(render);

			this.mouseConstraint = this.Matter.MouseConstraint.create(this.engine, { element: Render.canvas });
			this.Matter.World.add(this.engine.world, this.mouseConstraint);
			render.mouse = this.mouseConstraint.mouse;
		}

		private initWorld(): void {
			var cradle: any = this.Matter.Composites.newtonsCradle(280, 100, 5, 30, 200);
			this.Matter.World.add(this.engine.world, cradle);
			this.Matter.Body.translate(cradle.bodies[0],
				{
					x: -180,
					y: -100
				});

			cradle = this.Matter.Composites.newtonsCradle(280, 380, 7, 20, 140);
			this.Matter.World.add(this.engine.world, cradle);
			this.Matter.Body.translate(cradle.bodies[0],
				{
					x: -140,
					y: -100
				});
		}

		private onResize(): void {
			// 设置鼠标的坐标缩放
			this.Matter.Mouse.setScale(this.mouseConstraint.mouse, { x: 1 / (Laya.stage.clientScaleX * Laya.stage._canvasTransform.a), y: 1 / (Laya.stage.clientScaleY * Laya.stage._canvasTransform.d) });
		}
	}
}
new laya.Physics_NewtonsCradle();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值