【温故知新】——BABYLON.js学习之路·前辈经验(二)
前言:在上一篇隨筆BABYLON.js學(xué)習(xí)之路·前輩經(jīng)驗(yàn)(一)中回顧了組內(nèi)同事們長時(shí)間在Babylon開發(fā)實(shí)踐中的總結(jié)出的學(xué)習(xí)之路和經(jīng)驗(yàn),這一篇主要對(duì)開發(fā)中常見的一些功能點(diǎn)做一個(gè)梳理,這里只作為溫故知新。
| 一、相機(jī) |
弧形旋轉(zhuǎn)相機(jī) —— 使用鼠標(biāo)和光標(biāo)鍵將相機(jī)繞著一個(gè)三維點(diǎn)(此處時(shí)0坐標(biāo)處) 旋轉(zhuǎn)
參數(shù): 名稱, 水平角(alpha), 垂直角(beta), 半徑, 圍繞的目標(biāo), 場景
var camera = new BABYLON.ArcRotateCamera("ArcRotateCamera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);
cameras.target = new BABYLON.Vector3(0,0,0);
自由相機(jī) —— 你可以使用鼠標(biāo)和光標(biāo)鍵將之在場景中移動(dòng)
參數(shù): 名稱,位置,場景
var camera = new BABYLON.FreeCamera("FreeCamera", new BABYLON.Vector3(0, 1, -15), scene);
cameras.setTarget(new BABYLON.Vector3(0,0,0));
觸控相機(jī) —— 使用觸控設(shè)備來在場景中移動(dòng)它
參數(shù): 名稱,位置,場景
var camera = new BABYLON.TouchCamera("TouchCamera", new BABYLON.Vector3(0, 1, -15), scene);
//使用 setPosition() 把相機(jī)準(zhǔn)確地放置到我們期望的三維空間中的位置. 便捷的 setPosition() 方法將會(huì)做好剩下的事情
camera.setPosition(new BABYLON.Vector3(0, 15, -30));
限制相機(jī)參數(shù)
//對(duì)象上下移動(dòng)范圍 camera.lowerBetaLimit = Math.PI/2-Math.PI/6; camera.upperBetaLimit = Math.PI/2+Math.PI/6; //對(duì)象左右移動(dòng)范圍 camera.lowerAlphaLimit = -Math.PI/2-Math.PI/5; camera.upperAlphaLimit = -Math.PI/2+Math.PI/5; //對(duì)象遠(yuǎn)近移動(dòng)范圍 camera.lowerRadiusLimit = -Math.PI/3; camera.upperRadiusLimit = Math.PI/3; camera.wheelPrecision = 0.5; //電腦滾輪速度 越小靈敏都越高 camera.pinchPrecision = 1; //手機(jī)放大縮小速度 越小靈敏都越高
定向相機(jī) ——根據(jù)設(shè)備導(dǎo)向事件做出反應(yīng)的相機(jī) , 例如向前或向后傾斜的現(xiàn)代化移動(dòng)設(shè)備
var camera = new BABYLON.DeviceOrientationCamera("DevOr_camera", new BABYLON.Vector3(0, 0, 0), scene);
// 將相機(jī)對(duì)準(zhǔn)一個(gè)特地的位置
camera.setTarget(new BABYLON.Vector3(0, 0, -10));
// 設(shè)置相機(jī)對(duì)運(yùn)動(dòng)和旋轉(zhuǎn)的靈敏度
camera.angularSensibility = 10;
camera.moveSensibility = 10;
// 把相機(jī)固體在畫布上
camera.attachControl(canvas, true);
相機(jī)相關(guān)設(shè)置
//可旋轉(zhuǎn)相機(jī) camera.attachControl(canvas, true); //不可旋轉(zhuǎn)相機(jī) camera.detachControl(canvas); camera.inertia //相機(jī)慣性 camera.targetScreenOffset.x=40; //相機(jī)X軸偏移量 camera.targetScreenOffset.y=-70; //相機(jī)Y軸偏移量
相機(jī)與Mesh
//獲取攝像機(jī)能看到的mesh scene.activeCamera.getActiveMeshes() scene.getActiveMeshes() //判斷mesh是否在攝像機(jī)范圍內(nèi) scene.isActiveMesh(scene.meshes[2]) scene.activeCamera.isActiveMesh(scene.meshes[2])
| 二、燈光 |
漫反射(diffuse) 和 鏡面反射(specular) 屬性來控制任何光源的顏色:
點(diǎn)光源——點(diǎn)光源時(shí)世界空間中由一個(gè)唯一點(diǎn)定義的光源. 光源從該點(diǎn)向所有方向發(fā)射光線. 點(diǎn)光源的一個(gè)好例子是太陽.
var light0 = new BABYLON.PointLight("Omni0", new BABYLON.Vector3(1, 10, 1), scene);
light0.diffuse = new BABYLON.Color3(1, 0, 0);
light0.specular = new BABYLON.Color3(1, 1, 1);
定向光源——定向光建立在原點(diǎn)(0,0,0)的位置. 像點(diǎn)光源一樣
var light0 = new BABYLON.DirectionalLight("Dir0", new BABYLON.Vector3(0, -1, 0), scene);
light0.diffuse = new BABYLON.Color3(1, 0, 0);
聚光燈光源 ——一個(gè)聚光燈光源是通過一個(gè)位置 (第二個(gè)參數(shù)), 一個(gè)方向(第三個(gè)參數(shù)), 一個(gè)角度(第四個(gè)參數(shù)), 和一個(gè)衰減指數(shù)(第五個(gè)參數(shù))定義的. 這些值定義了一個(gè)圓椎體,光源從中發(fā)射出來
角度(弧度單位)定義了聚光燈光源椎體光束的大小(照明q區(qū)域), 同時(shí)指數(shù)定義了光隨距離(光照射的距離)衰減的速度
一個(gè)帶紅色漫反射的白色鏡面反射光聚光燈光源,椎體0.8弧度,衰減指數(shù)2
var light0 = new BABYLON.SpotLight("Spot0", new BABYLON.Vector3(0, 30, -10), new BABYLON.Vector3(0, -10, 0), 0.8, 2, scene);
light0.diffuse = new BABYLON.Color3(1, 0, 0);
light0.specular = new BABYLON.Color3(1, 1, 1);
半球狀光源 ——半球光源是模式現(xiàn)實(shí)環(huán)境光的簡單方法. 半球光源是通過一個(gè)朝天的方向(構(gòu)造函數(shù)的第二個(gè)參數(shù))和三種顏色定義, 一種顏色提供給漫反射(天空的顏色-朝上的像素/面片),一種是給地面的 (朝下的像素/面片的顏色), 以及一種給鏡面反射的
白/黑半球光源 - 朝上的像素白色(漫反射), 朝下的像素黑色(底色)
var light0 = new BABYLON.HemisphericLight("Hemi0", new BABYLON.Vector3(0, 1, 0), scene);
light0.diffuse = new BABYLON.Color3(1, 1, 1);
light0.specular = new BABYLON.Color3(1, 1, 1);
light0.groundColor = new BABYLON.Color3(0, 0, 0);
scene.lights[0].excludedMeshes.push(mesh)// mesh不受燈光影響
清除燈光
if (scene.lights[0]) {
scene.lights[0].setEnabled(false);
scene.lights[0].dispose();
}
| 三、創(chuàng)建模型 |
創(chuàng)建一個(gè)球體
參數(shù): 名字, 細(xì)分段數(shù) (高度細(xì)節(jié)或不需), 大小, 將被放到的場景, 是否可更新?(如果該網(wǎng)格后面必須被更新) 和可選的面朝向(參見下面)
如果你需要默認(rèn)的表現(xiàn)那么最后兩個(gè)參數(shù)可以忽略:
var sphere = BABYLON.Mesh.CreateSphere("sphere", 10.0, 10.0, 場景, false, BABYLON.Mesh.DEFAULTSIDE);
創(chuàng)建一個(gè)平面
參數(shù): 名字, 大小, 和將被放到的場景, 是否可更新?(如果該網(wǎng)格后面必須被更新) 和可選的面朝向(參見下面)
如果你需要默認(rèn)的表現(xiàn),那么最后兩個(gè)參數(shù)可以忽略:
var plane = BABYLON.Mesh.CreatePlane("plane", 10.0, scene, false, BABYLON.Mesh.DEFAULTSIDE);
創(chuàng)建一個(gè)盤片(或一個(gè)規(guī)則多邊形)
參數(shù): 名字, 半徑, 邊數(shù), 場景, 可更新否和可選的朝向(參見下面)
如果你需要默認(rèn)的表現(xiàn),那么最后兩個(gè)參數(shù)參數(shù)可以忽略:
var disc = BABYLON.Mesh.CreateDisc("disc", 5, 30, scene, false, BABYLON.Mesh.DEFAULTSIDE);
創(chuàng)建一個(gè)圓柱體
參數(shù): 名稱, 高度, 頂直徑, 底直徑, 邊數(shù), 高向細(xì)分度, 場景, 可更新否和可選的朝向(參見下面)
如果你需要默認(rèn)表現(xiàn),那么最后兩個(gè)參數(shù)可以忽略:
var cylinder = BABYLON.Mesh.CreateCylinder("cylinder", 3, 3, 3, 6, 1, scene, false, BABYLON.Mesh.DEFAULTSIDE);
創(chuàng)建一個(gè)環(huán)面體
參數(shù): 名稱, 直徑, 厚度, 邊數(shù)(高度細(xì)節(jié)或不是), 場景, 可更新否和可選的朝向(參見下面)
如果你使用默認(rèn)表現(xiàn)那么最后兩個(gè)參數(shù)可忽略 :
var torus = BABYLON.Mesh.CreateTorus("torus", 5, 1, 10, scene, false, BABYLON.Mesh.DEFAULTSIDE);
創(chuàng)建一個(gè)結(jié)
參數(shù): 名稱, 半徑, tube, 半徑上分段數(shù), tubularSegments, p, q, 場景, 可更新否和可選的朝向(參見下面)
如果你使用默認(rèn)的表現(xiàn)那么最后的兩個(gè)參數(shù)可以忽略 :
var knot = BABYLON.Mesh.CreateTorusKnot("knot", 2, 0.5, 128, 64, 2, 3, scene, false, BABYLON.Mesh.DEFAULTSIDE);
創(chuàng)建一個(gè)地面
參數(shù): 名稱, 寬度, 縱深, 子分段數(shù), 場景
var ground = BABYLON.Mesh.CreateGround("ground", 6, 6, 2, scene);
創(chuàng)建一個(gè)SubMesh
new SubMesh(materialIndex,verticesStart,verticesCount,indexStart,indexCount,mesh,renderingMesh,createBoundingBox) //materialIndex 數(shù) 要使用的材料的索引(此索引用于在多材質(zhì)的subMaterials集合內(nèi)找到正確的材質(zhì)) //verticesStart 數(shù) //verticesCount 數(shù) 使用的頂點(diǎn)數(shù) //indexStart 任何要使用的第一個(gè)indice的索引 //indexCount 數(shù) 指數(shù)計(jì)數(shù) //Mesh @param mesh 網(wǎng)格 摘要 //renderingMesh 網(wǎng)格 如果已定義,則用于代替網(wǎng)格參數(shù)(可選的)
創(chuàng)建空Mesh
new BABYLON.Mesh("a", scene);
其它Mesh相關(guān)
合并網(wǎng)格
var boxes_merged = BABYLON.Mesh.MergeMeshes(scene.getMeshesByTags("box"));
boxes_merged.position.x = 0;
position 是mesh的位置
absolutePosition是 mesh軸的位置
如果將diameterTop設(shè)置為零,則會(huì)得到錐體而不是圓柱體。示例:
var cone = BABYLON.MeshBuilder.CreateCylinder("cone", {diameterTop: 0, tessellation: 4}, scene);
獲取mesh數(shù)據(jù)類型——位置/uv/color/材質(zhì)
mesh.getVerticesDataKinds()
| 四、動(dòng)畫 |
創(chuàng)建動(dòng)畫對(duì)象
參數(shù)1 - 動(dòng)畫的名稱,僅此而已。
參數(shù) 2 - 關(guān)心的屬性。這個(gè)可以是網(wǎng)格的任何屬性,取決于你要修改什么。此處我們想在X軸方向上放大對(duì)象, 所以此處使用“scaling.x”。
參數(shù) 3 - 請(qǐng)求的每秒幀數(shù):這個(gè)動(dòng)畫里最大 的FPS。
參數(shù) 4 - 修改的類型。此處你決定開始修改什么類型的數(shù)據(jù):floating(比如是浮點(diǎn)數(shù)),一個(gè)向量(比如是方向),或四元數(shù)。具體的值會(huì)是:
BABYLON.Animation.ANIMATIONTYPE_FLOAT
BABYLON.Animation.ANIMATIONTYPE_VECTOR2
BABYLON.Animation.ANIMATIONTYPE_VECTOR3
BABYLON.Animation.ANIMATIONTYPE_QUATERNION
BABYLON.Animation.ANIMATIONTYPE_MATRIX
BABYLON.Animation.ANIMATIONTYPE_COLOR3
參數(shù) 5 - 最后, 你需要決定并輸入這個(gè)動(dòng)畫的行為類型,這些會(huì)決定動(dòng)畫的受限(比如:當(dāng)?shù)阶詈笠粠瑫r(shí)是否繼續(xù),是否重新開始,或者停止):
使用之前的值然后遞增: BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE
從初始值重啟 BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE
保持最后的值: BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT
var animationBox = new BABYLON.Animation("myAnimation", "scaling.x", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
創(chuàng)建動(dòng)畫
CreateAndStartAnimation(name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd)
BABYLON.Animation.CreateAndStartAnimation("mesh", mesh[0], 'rotation.y', 30, 150, mesh[0].rotation.y, mesh[0].rotation.y+(Math.PI*2), 1);
// name 姓名
// node 節(jié)點(diǎn)(目標(biāo))
// targetProperty 目標(biāo)屬性
// framePerSecond 幀每秒
// totalFrame 總共幀數(shù)
// from 開始狀態(tài)
// to 結(jié)束狀態(tài)
// loopMode 循環(huán)模式(次數(shù)) 可選
// easingFunction EasingFunction 可選
創(chuàng)建一個(gè)動(dòng)畫以將屬性的當(dāng)前值插入給定目標(biāo)
new InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) // triggerOptions 觸發(fā)器選項(xiàng) // target 目標(biāo) // propertyPath 目標(biāo)的屬性 // value 目標(biāo)的值 // duration 持續(xù)時(shí)間 // condition 條件 // stopOtherAnimations 停止其他動(dòng)畫 boolean (可選的)
此操作是一個(gè)容器。 您可以使用它在同一觸發(fā)器上同時(shí)執(zhí)行多個(gè)操作。 children屬性必須是一個(gè)操作數(shù)組
new CombineAction(triggerOptions, children, condition) : // triggerOptions:觸發(fā)器選項(xiàng) // children : The childrens actions // condition : 執(zhí)行動(dòng)作的條件(可選)
創(chuàng)建新的設(shè)置值操作
new SetValueAction(triggerOptions, target, propertyPath, value, condition) //triggerOptions 觸發(fā)器選項(xiàng) //target 行動(dòng)目標(biāo) //propertyPath 行動(dòng)目標(biāo) //value 動(dòng)作值
new DoNothingAction(triggerOptions, condition) //不作為
new SetStateAction(triggerOptions, target, value, condition)
BABYLON.IncrementValueAction:向數(shù)字屬性添加指定的值
IncrementValueAction(trigger, target, propertyPath, value, condition)
狀態(tài)條件構(gòu)造函數(shù)
new StateCondition(actionManager, target, value) //舉例 var condition1 = new BABYLON.StateCondition(sphere.actionManager, light1, "off");
動(dòng)畫API
animation.stop() // 完全停止, 要想開始動(dòng)畫,就要重建動(dòng)畫 animation.pause() // 動(dòng)畫暫停,保存幀數(shù) animation.reset() // 動(dòng)畫回到第0幀 , 但動(dòng)畫沒啟動(dòng) animation.restart() // 動(dòng)畫啟動(dòng), 從暫停的幀數(shù)開始
| 五、貼圖 |
貼圖視頻
var ground = BABYLON.Mesh.CreateGround("ground1", 6, 6, 2, scene);
var mat = new BABYLON.StandardMaterial("mat", scene);
var videoTexture = new BABYLON.VideoTexture("video", ["video/babylonjs.mp4"], scene, true, true);
mat.diffuseTexture = videoTexture;
ground.material = mat;
貼圖翻轉(zhuǎn)
materialSphere4.diffuseTexture.vOffset = 0.1; //垂直翻轉(zhuǎn) materialSphere4.diffuseTexture.uOffset = 0.4; //水平翻轉(zhuǎn) materialSphere6.backFaceCulling = false; //背面貼圖顯示 materialSphere5.diffuseTexture.hasAlpha = true;//適用png的透明(png比較消耗性能)
貼圖紋理
reflectionTexture 反射紋理
MirrorTexture 鏡子紋理
mirror.material.reflectionTexture = new BABYLON.MirrorTexture("mirror", 1024, scene, true);
mirror.material.reflectionTexture.mirrorPlane = new BABYLON.Plane(0, -1.0, 0, -2.0);
bumpMaterial 凹凸紋理
var bumpMaterial = new BABYLON.StandardMaterial("texture1", scene);
bumpMaterial.diffuseColor = new BABYLON.Color3(0, 0, 1);//Blue
bumpMaterial.bumpTexture = new BABYLON.Texture("textures/normalMap.jpg", scene);
getTextureCoordinates() 計(jì)算所選點(diǎn)的紋理坐標(biāo); 這些將作為Vector2紋理空間返回,這意味著它的坐標(biāo)將在0和1之間
| 六、旋轉(zhuǎn)軸 |
門的旋轉(zhuǎn)軸
var door=scene.getMeshByName("56_Box03");
var doorParent=new BABYLON.Mesh.CreateBox("doorParent",100,scene);
doorParent.position=door.position.add(new BABYLON.Vector3(300,0,0));
door.parent=doorParent;
door.position=new BABYLON.Vector3.Zero().add(new BABYLON.Vector3(-300,0,0))
模型邊框
plan.renderOutline = true; plan.outlineWidth = 10; plan.outlineColor = new BABYLON.Color3(0, 1, 1);
| 七、材質(zhì) |
網(wǎng)格材質(zhì)
grid = new BABYLON.GridMaterial("grid", scene);
scene.getMeshByName('woshichuanglian').material= grid;
grid.gridRatio = 1;
grid.majorUnitFrequency = 2;
grid.minorUnitVisibility = 4;
grid.opacity = 0.58;
grid.mainColor = new BABYLON.Color3(1,1,1)
grid.lineColor = new BABYLON.Color3(1,1,1)
多材質(zhì)
var multi = new BABYLON.MultiMaterial('multi' , scene);
var hdrTexture = new BABYLON.HDRCubeTexture("img/room.hdr", scene, 512);
var metal = new BABYLON.PBRMaterial("metal", scene);
metal.reflectionTexture = hdrTexture; //反射紋理
metal.directIntensity = 3; //直接燈的強(qiáng)度
metal.specularIntensity = 5;
metal.emissiveIntensity = 100; //材料的發(fā)射部分的強(qiáng)度。 這有助于控制發(fā)光效果而不修改發(fā)光顏色。
metal.environmentIntensity = 1; //環(huán)境的強(qiáng)度,例如環(huán)境將會(huì)點(diǎn)亮對(duì)象多少 無論是通過粗糙材料的諧波或通過對(duì)閃亮材料的補(bǔ)償
metal.cameraExposure = 1.2; //相機(jī)曝光 亮度
metal.cameraContrast = 1; //相機(jī)對(duì)比度 明暗對(duì)比
metal.microSurface =0.9; //反射出的物體的細(xì)致程度
metal.useRadianceOverAlpha = true; //指定材料會(huì)將反射亮點(diǎn)保持在透明表面上
metal.reflectivityColor = new BABYLON.Color3(1, 1, 1); //反射的物體
metal.albedoColor = new BABYLON.Color3(1, 1, 1); //反射出的光
mesh[0].material = metal;
如果紋理有alpha 設(shè)置hasAlpha為true
materialSphere1.diffuseTexture.hasAlpha = true; materialSphere1.useAlphaFromDiffuseTexture = true //alpha混合
所產(chǎn)生的顏色與漫反射顏色相乘
如果要使用烘烤成紋理的光照貼圖,這一點(diǎn)尤其有用。您可以使用ambientColor屬性指定純色:
materialSphere1.ambientColor = new BABYLON.Color3(1, 0.2, 0.7);
materialSphere1.ambientTexture = new BABYLON.Texture("grass.png", scene);
材質(zhì)屬性
directIntensity:控制材質(zhì)反射的漫反射和鏡面反射量。
emissiveIntensity:控制材質(zhì)發(fā)射的發(fā)射光的水平。
environmentIntensity:控制來自環(huán)境的反射光的水平。
specularIntensity:由于材質(zhì)仍然使用像閃光計(jì)算那樣的blinn Phong,這可以幫助降低材料的鏡面水平而不會(huì)影響反射率。
pbr.cameraExposure = 0.66; //相機(jī)曝光 pbr.cameraContrast = 1.66; //相機(jī)對(duì)比度
materialSphere.albedoColor = new BABYLON.Color3(0.2, 0.9, 1.0); //球顏色 materialSphere.reflectivityColor = new BABYLON.Color3(0.8, 0.8, 0.8); //反射率顏色 ,黑色鏡面將意味著幾乎沒有反射,白色將從完美的鏡子接近 materialSphere.microSurface = 0.98;//越高,光澤度越高 反射越清晰 materialSphere.usePhysicalLightFalloff = false; //光澤度存儲(chǔ)在反射率圖的alpha通道中,可以防止在一種材料上具有恒定的光澤度 materialSphere.useMicroSurfaceFromReflectivityMap = false; pbr.useMicroSurfaceFromReflectivityMapAlpha = true;
注:環(huán)境色彩需要設(shè)置場景的環(huán)境顏色,給予環(huán)境背景照明。
scene.ambientColor = new BABYLON.Color3(1, 1, 1);
TexturesMode
coordinatesMode: int (0 = explicit, 1 = spherical, 2 = planar, 3 = cubic, 4 = projection, 5 = skybox), projectionMat.reflectionTexture.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
billboardMode
"billboardMode": int (0 = None, 1 = X, 2 = Y, 4 = Z, 7 = All), CreatePlane.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL; //始終面向你 廣告板
其它
material.maxSimultaneousLights = lightsCount; //最大同時(shí)能接受燈光
material.disableLighting = true;//材質(zhì)不收燈光影響
mat.diffuseColor = BABYLON.Color3.FromInts(121,189,224);
mat.diffuseColor = BABYLON.Color3.FromeHexDtring("#000000");
注意: PBRMaterial不受燈光影響
| 八、高度地圖 |
var ground = BABYLON.Mesh.CreateGroundFromHeightMap("ground", "worldHeightMap.jpg", 200, 200, 250, 0, 10, scene, false, successCallback);
// 名稱
// 高度地圖圖片網(wǎng)址
// 此網(wǎng)格的大小:寬度 高度
// 細(xì)分?jǐn)?shù)量:增加此網(wǎng)格的復(fù)雜性,以提高其視覺質(zhì)量:
// 最小高度:網(wǎng)格的最低水平
// 最大高度:網(wǎng)格的最高水平
// 場景:實(shí)際場景
// 可更新:表示如果此網(wǎng)孔可以動(dòng)態(tài)在未來被更新(布爾)
// successCallback:將在創(chuàng)建高度圖并創(chuàng)建頂點(diǎn)數(shù)據(jù)后調(diào)用。它是一個(gè)具有網(wǎng)格作為其第一個(gè)變量的函數(shù)。
最后,當(dāng)我們的新網(wǎng)格準(zhǔn)備好了,我們只需應(yīng)用我們的材料:
ground.material = groundMaterial;
| 九、發(fā)光 |
官方文檔
var hl = new BABYLON.HighlightLayer("hl1", scene);
hl.addMesh(box, BABYLON.Color3.Green());
hl.isEnabled = true;
想讓體積散射光放到mesh上時(shí) , 必須給mesh加上material
var godrays = new BABYLON.VolumetricLightScatteringPostProcess('godrays',1, camera, sphere, 100, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, true);
| 十、展示邊界 |
mesh.showBoundingBox =true;
| 十一、粒子系統(tǒng) |
創(chuàng)建粒子系統(tǒng)
var particleSystem = new BABYLON.ParticleSystem("particles", 2000, scene, customEffect);
//第一個(gè)參數(shù)是名稱,第二個(gè)參數(shù)是粒子的最大數(shù)量,第三個(gè)參數(shù)是場景,
//可選的第四個(gè)參數(shù)是對(duì)粒子的著色效果的引用,覆蓋默認(rèn)著色器
// 把blendmode換成下面這個(gè)就可以了。但是顏色好像有影響
BLENDMODE_ONEONE //- colors are added without alpha affecting the result; //粒子顏色不受alpha影響。
BLENDMODE_STANDARD //- colors are added using particle’s alpha. //粒子顏色使用粒子本身alpha
| 十二、天空盒 |
創(chuàng)建Skybox天空盒
var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, scene);
var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", scene);
hdrSkyboxMaterial.backFaceCulling = false;
hdrSkyboxMaterial.reflectionTexture = hdrTexture.clone();
hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
hdrSkyboxMaterial.microSurface = 1.0;
hdrSkyboxMaterial.cameraExposure = 0.6;
hdrSkyboxMaterial.cameraContrast = 1.6;
hdrSkyboxMaterial.disableLighting = true;
hdrSkybox.material = hdrSkyboxMaterial;
hdrSkybox.infiniteDistance = true;
skybox.infiniteDistance = true; //無線距離
skybox.renderingGroupId = 0;
skyboxMaterial.disableLighting = true; //對(duì)光照沒反應(yīng), 不能照明
天空盒圖片命名
n開頭的都在相應(yīng)軸的反方向:_nx_ny _nz
p開頭的都在相應(yīng)軸的正方向:_px _py _pz
場景默認(rèn)天空盒
scene.imageProcessingConfiguration.contrast = 1; //對(duì)比度 scene.imageProcessingConfiguration.exposure = 1; //曝光 scene.imageProcessingConfiguration.toneMappingEnabled = true; //色調(diào)映射啟用
場景天空盒圖片
var hdrTexture = new BABYLON.CubeTexture.CreateFromPrefilteredData("images/environment.dds", scene); //場景天空盒的圖片, 可以是.dds文件
var hdrTexture =new BABYLON.CubeTexture('images/cubemap/cubemap', scene); //場景天空盒的圖片,可以是圖片
hdrTexture.gammaSpace = false; //貼圖的空間,不知道干什么用
繪制場景天空盒
本質(zhì)上就是創(chuàng)建了一個(gè)很大的天空盒, 用了pbr材質(zhì), 然后貼了材質(zhì)并且模糊, 就是這樣:)
注意: 在這只場景天空盒子的時(shí)候, 場景內(nèi)默認(rèn)的pbr材質(zhì)的反射和折射貼圖,默認(rèn)為場景天空盒的貼圖
var sky = scene.createDefaultSkybox(hdrTexture, true, 100000, 1); // 第一個(gè)參數(shù)是文件, 第二個(gè)參數(shù)是pbr材質(zhì), 第三是范圍, 半徑, 第四是模糊程度(0是不模糊)
創(chuàng)建場景默認(rèn)的燈光和相機(jī)
scene.createDefaultCameraOrLight(true, true, true);
| 十三、陰影 |
var shadowGenerator = new BABYLON.ShadowGenerator(2048, light2); shadowGenerator.setDarkness(0); //陰影黑暗程度 shadowGenerator.usePoissonSampling = true; plane.receiveShadows = true; shadowGenerator.getShadowMap().renderList.push(mesh[0]);
| 十四、反射 |
選擇要反射的物體
var probe = new BABYLON.ReflectionProbe("main", 512, scene);
probe.renderList.push(plane);
probe.attachToMesh(mesh);
var mainMaterial = new BABYLON.ReflectionProbe("meta2", scene);
mainMaterial.diffuseColor = new BABYLON.Color3(1, 0.5, 0.5);
mainMaterial.reflectionTexture = probe.cubeTexture;
mainMaterial.reflectionFresnelParameters = new BABYLON.FresnelParameters();
mainMaterial.reflectionFresnelParameters.bias = 0.02;
mesh[0].material = mainMaterial;
鏡面反射
設(shè)置反射材質(zhì)時(shí)候,如果反射材質(zhì)沒出現(xiàn),看看是不是光強(qiáng)度太大【還可以設(shè)置材質(zhì)不受光照影響】
var material3 = new BABYLON.StandardMaterial('met3' , scene)
material3.reflectionTexture = new BABYLON.MirrorTexture('mirror' ,512, scene, true); //鏡子紋理
material3.reflectionTexture.mirrorPlane= new BABYLON.Plane(0,-1.0,0,-10.0); //反射層
material3.reflectionTexture.renderList = [plane]; //添加把要反射的東西
material3.reflectionTexture.level = 0.6;
mesh[0].material = material3;
| 十五、折射 |
平面
var refractionTexture = new BABYLON.RefractionTexture("th", 1024, scene);
refractionTexture.renderList.push(yellowSphere);
refractionTexture.renderList.push(greenSphere);
refractionTexture.renderList.push(ground);
refractionTexture.refractionPlane = new BABYLON.Plane(0, 0, -1, 0);
refractionTexture.depth = 2.0;
非平面
var probe = new BABYLON.ReflectionProbe("main", 512, scene);
probe.renderList.push(yellowSphere);
probe.renderList.push(greenSphere);
probe.renderList.push(blueSphere);
probe.renderList.push(mirror);
mainMaterial.refractionTexture = probe.cubeTexture;
得要有refraction
materialSphere3.indexOfRefraction = 1; //折射率越大, 鏡片越薄,看起來越折射
| 十六、菲涅爾 |
只有standardMaterial 才有fresnel
StandardMaterial.diffuseFresnelParameters StandardMaterial.opacityFresnelParameters StandardMaterial.reflectionFresnelParameters StandardMaterial.emissiveFresnelParameters StandardMaterial.refractionFresnelParameters
FresnelParameters
isEnabled 激活或停用菲涅爾效應(yīng)
leftColor 定義邊緣上使用的顏色
rightColor 定義中心使用的顏色
bias 定義施加到計(jì)算的菲涅爾項(xiàng)的偏差 數(shù)值越大越模糊,能容忍的誤差越大
power 菲涅耳期的指數(shù)的權(quán)力 越大界限越明顯,中心地帶越清晰
| 十七、位置 |
pilot.translate(vector, distance, space) //space == BABYLON.Space.WORLD || BABYLON.Space.LOCAL greenSphere.setPivotMatrix(BABYLON.Matrix.Translation(0, 0, 3)); //在不改變旋轉(zhuǎn)軸的情況下,移動(dòng)位置 greenSphere.setPivotPoint() // 改變軸心的位置 greenSphere.position = new BABYLON.Vector3(0,0,3) //旋轉(zhuǎn)軸隨著物體的改變而改變
| 十八、軸 |
BABYLON.Space.LOCAL //本地軸 BABYLON.Space.WORLD //世界軸 sphere.flipFaces(); //法線反向
通過如下創(chuàng)建四元數(shù)來設(shè)置rotationQuaternion屬性給定軸和角度
var axis = new BABYLON.Vector3(2, 6, 4); var angle = 0; mesh.rotationQuaternion = new BABYLON.Quaternion.RotationAxis(axis, angle);
| 十七、babylon截屏工具 |
var size = { 1000, height: 900} // 512,size = { precision: 2 };
BABYLON.Tools.CreateScreenshot(engine, touchCamera, size);
| 十八、instance實(shí)例 |
var mesh = newMeshes[0];
for (var index = 0; index < 100; index++) {
var newInstance = mesh.createInstance("i" + index);
}
實(shí)例具有與網(wǎng)格相同的材質(zhì),支持碰撞,挑選,渲染和陰影
position
rotation
rotationQuaternion
setPivotMatrix
scaling
| 十九、相機(jī)視圖(多相機(jī)) |
BABYLON.Viewport = function (x, y, width, height); camera.viewport = new BABYLON.Viewport(0, 0, 1, 1); camera2.viewport = new BABYLON.Viewport(0,0, 0.5, 0.5); scene.activeCameras.push(camera); scene.activeCameras.push(camera2);
| 二十、視圖清晰程度 |
engine.setHardwareScalingLevel(0.2) //像素精確度,數(shù)值越大,越模糊
| 二十一、GUI |
var advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateForMesh(plane);
var text1 = new BABYLON.GUI.TextBlock();
text1.text = "Hello world";
text1.color = "green";
text1.fontSize =80;
text1.textHorizontalAlignment = 0;
advancedTexture.addControl(text1);
var text2 = new BABYLON.GUI.TextBlock();
text2.text = "1111111";
text2.color = "green";
text2.fontSize =80;
text2.textHorizontalAlignment = 1;
advancedTexture.addControl(text2);
var image = new BABYLON.GUI.Image("but", "./images/ruler.png");
image.width = 0.2;
image.height = 0.2;
advancedTexture.addControl(image);
| 二十二、動(dòng)態(tài)貼圖 |
var dynTexture = new BABYLON.DynamicTexture('texture', 512, scene, true);
dynTexture.hasAlpha = true ;
var ctx = dynTexture.getContext();
var font = '1.2rem Arial';
var size = dynTexture.getSize();
var img = new Image();
//img.src = './images/ruler.png';
//dynTexture.drawText('hello, worls',50,70,font, 'green','red');
//dynTexture.drawText('arre',50,100,font, 'green','red');
img.src = './images/content.png';
img.onload = function () {
ctx.drawImage(img,0,0,size.width, size.height);
//ctx.drawImage(img,0,0);
dynTexture.update(false);
};
| 二十三、視差映射 |
您可以通過以下材料使用視差映射:
StandardMaterial
PBRMaterial
useParallax:啟用Bump上的視差映射。如果您沒有分配一個(gè)bumpTexture,這些屬性將不會(huì)有任何影響。
useParallaxOcclusion:啟用視差遮擋,設(shè)置此屬性時(shí),還必須將useParallax設(shè)置為true。
allaxScaleBias:應(yīng)用縮放因子,確定哪個(gè)“深度”應(yīng)該代表高度圖。視差值在0.05和0.1之間是合理的,您可以使用視差遮擋達(dá)到0.2。
| 二十四、獲取二維坐標(biāo) |
獲取模型的在畫布上面的二維坐標(biāo)
var mesh2d = BABYLON.Vector3.Project(mesh.position, BABYLON.Matrix.Identity(), scene.getTransformMatrix(), camera.viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight())); console.log(mesh2d.y) console.log(mesh2d.x)
在最小寬度為760所以小于760的尺寸如移動(dòng)端 必須使用百分比獲取坐標(biāo)
var mesh2d = BABYLON.Vector3.Project(mesh.position, BABYLON.Matrix.Identity(), scene.getTransformMatrix(), camera.viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight())); console.log(mesh2d.y/engine.getRenderHeight()*100+"%") console.log(mesh2d.x/engine.getRenderWidth()*100+"%")
| 二十五、點(diǎn)擊事件 |
點(diǎn)擊事件
scene.onPointerObservable.add(function (e) {
console.log(e.pickInfo.pickedMesh.name)
}, BABYLON.PointerEventTypes.POINTERDOWN);
點(diǎn)擊類型
scene.onPointerObservable.add((pointerInfo) => {
if(pointerInfo.pickInfo.hit){
console.log(pointerInfo.pickInfo.pickedMesh.name)
}
switch (pointerInfo.type) {
case BABYLON.PointerEventTypes.POINTERDOWN:
console.log("POINTER DOWN");
break;
case BABYLON.PointerEventTypes.POINTERUP:
console.log("POINTER UP");
break;
case BABYLON.PointerEventTypes.POINTERMOVE:
console.log("POINTER MOVE");
break;
case BABYLON.PointerEventTypes.POINTERWHEEL:
console.log("POINTER WHEEL"); //滾輪
break;
case BABYLON.PointerEventTypes.POINTERPICK:
console.log("POINTER PICK");
break;
case BABYLON.PointerEventTypes.POINTERTAP:
console.log("POINTER TAP");
break;
case BABYLON.PointerEventTypes.POINTERDOUBLETAP:
console.log("POINTER DOUBLE-TAP"); //雙擊
break;
}
});
scene.onKeyboardObservable.add((kbInfo) => {
switch (kbInfo.type) {
case BABYLON.KeyboardEventTypes.KEYDOWN:
console.log("KEY DOWN: ");
break;
case BABYLON.KeyboardEventTypes.KEYUP:
console.log("KEY UP: ");
break;
}
});
| 二十六、babylon生成png |
創(chuàng)建網(wǎng)格后
//BABYLON.Tools.CreateScreenshotUsingRenderTarget(engine, camera, size, function(data){
// 獲取的圖片
//})
BABYLON.Tools.CreateScreenshotUsingRenderTarget(engine, scene.activeCamera, 400);
創(chuàng)建網(wǎng)格時(shí)
BABYLON.Tools.CreateScreenshot(engine, camera, 400);
| 二十七、手機(jī)調(diào)試 |
Vorlon.js安裝過程非常簡單,只需下面幾步即可完成:
1、從npm安裝vorlon.js服務(wù)器: $ npm i -g vorlon;
2、運(yùn)行vorlon.js服務(wù)器: $ vorlon,此時(shí)可以在瀏覽器中打開http://localhost:1337,查看儀表盤頁面;
3、向應(yīng)用添加script標(biāo)簽,啟用vorlon.js:<script src="http://10.0.4.102:1337/vorlon.js"></script>
| 二十八、異步加載 |
var anim = scene.beginAnimation(box1, 0, 100, false);
console.log("before");
await anim.waitAsync(); //等待異步執(zhí)行完畢, 在執(zhí)行下一步
console.log("after");
| 二十九、閉塞查詢 |
官方文檔
mesh.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE; mesh.isOccluded = true; mesh.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC;
| 三十、其它鏈接 |
https://doc.babylonjs.com/how_to/how_to_use_lens_flares 鏡頭光暈
https://www.babylonjs-playground.com/1 二維坐標(biāo)轉(zhuǎn)成三維坐標(biāo)
https://www.babylonjs-playground.com/ // 變形
https://www.babylonjs-playground.com/
https://www.babylonjs-playground.com/
https://www.babylonjs-playground.com/ 煙花
版權(quán)聲明:本文整理只做學(xué)習(xí),未經(jīng)允許不得轉(zhuǎn)載
總結(jié)
以上是生活随笔為你收集整理的【温故知新】——BABYLON.js学习之路·前辈经验(二)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何取网名,网名昵称好听542个
- 下一篇: 小班游戏教案《老鹰捉小鸡》