Home  >  Article  >  Web Front-end  >  How to use H5's WebGL to implement roaming animation in 3D virtual computer room

How to use H5's WebGL to implement roaming animation in 3D virtual computer room

php中世界最好的语言
php中世界最好的语言Original
2018-01-30 09:44:362393browse

This time I will show you how to use H5's WebGL to realize the roaming animation of the 3D virtual computer room. , the following is a practical case, let’s take a look. The use of first-person in 3D should refer to the use of first-person in shooting games. First-person shooters (FPS) are a type of video game based on the first-person perspective and around guns and other weapons; That is, players experience the action through the eyes of the protagonist. Since the genre's inception, advanced 3D and pseudo-3D graphics have challenged hardware development, and multiplayer gaming has become indispensable. Nowadays, museums or companies often use 3D animation to make promotional videos, etc. The biggest advantage of 3D animation interpretation is that it gives people a real feeling in terms of content and form. It is more intuitive than graphic works and more realistic than 2D animation, so it can give viewers the feeling of being in the advertising environment, greatly enhancing the persuasiveness of advertising. The development of 3D technology even challenges the audience's ability to distinguish, causing the audience's judgment to drift between virtual and reality.

Moreover, the application of 3D special effects provides a broader thinking space for creativity, becomes a reliable guarantee for creative execution, and enriches the form and style of creativity. According to the performance appeal of the advertising theme, a dreamlike and magical atmosphere can be created to stimulate and impress the audience, thereby achieving the purpose of communicating with the audience.

The 3D animated promotional video combines 3D animation, special effects shots, corporate videos, photos, future prospects and other content through post-production synthesis, dubbing, and commentary to form an intuitive, vivid, and popular high-grade corporate advertising video to make a difference in society. People at this level have a positive, positive, and good impression of the company, thereby establishing goodwill and trust in the company, and trusting the company's products or services.

Now 3D is developing so rapidly thanks to mankind’s pursuit of “reality”, so learning to use 3D well is an indispensable part of future success.

The idea of ​​the example in this article is to enter a computer room for a visit. The action of opening the door cannot be more dynamic. Coupled with appropriate turns, it basically completely simulates the effect of people visiting the computer room. Another advantage is that if you want to demonstrate it to your boss without having to operate it, your boss will definitely be very satisfied with this cool effect!

The "reset" and "start" buttons on the interface are buttons directly added to the body, and click events are added to these two buttons:

<div></div><div></div>

The entire scene is composed of It is formed by building 3D components encapsulated by HT. Constructing such a large scene requires a certain amount of code. To simplify, I took out the scene separately and used the ht.JSONSerializer class encapsulated by HT to serialize the scene into json. The code only The generated json file is introduced. In order to make it clearer, let me give an example here, assuming that the 3D scene has been built:

dm = new ht.DataModel();g3d = new ht.graph3d.Graph3dView(dm);//.......构建好场景dm.serialize();//可以填入number参数,作为空格缩进值

Now that we have set up the environment and converted it into a json file, the code It is difficult to control. In this case, we will deserialize the DataModel data

model

. The function of this

function

is to convert the json format into an object and deserialize it. The object is passed into the DataModel data model. For details, please refer to the HT for Web serialization manual:

var g3d = window.g3d = new ht.graph3d.Graph3dView(),   
dataModel = g3d.dm(),   
view = g3d.getView(),   
path = null;g3d.setMovableFunc(function(data) {    return false;});
g3d.setVisibleFunc(function(data) {   
if (data.getName() === "path") {      
 return false;   
}   
return true;});
g3d.setEye([523, 5600, 8165]);g3d.setFar(60000);dataModel.deserialize(json);
We currently need to operate the "door" in the scene and the route "path" we will take to traverse the DataModel data. Model, get these two data:
for (var i = 0; i < dataModel.size(); i++) {   
var data = dataModel.getDatas().get(i);  
 if (data.getName() === "门")
{//json中设置的名称      
window.door = data;   
}   
if (data.getName() === "path")
{       
path = data;   
}   
if (window.door && path)
{//获取到door 和 path 的data之后就跳出循环       
break;  
 }}
In simple terms, there are only four actions in this example, "reset" to return to the origin, "start action", "move forward", and "stop". Click the "Start" button. In the "Start Action" we only do one action, the "Open the Door" action. After the action is completed, call the "forward" function to move forward:

function startAnim() {
    
if (window.isAnimationRunning)
{       
return;  
 }   
reset();   
window.isAnimationRunning = true;//动画是否正在进行    ht.Default.startAnim({      
 frames: 30, // 动画帧数,默认采用`ht.Default.animFrames`。       
interval: 20, // 动画帧间隔,默认采用`ht.Default.animInterval`。          
finishFunc: function() {// 动画结束后调用的函数。           
forward();       
},        
action: function(t){ // action函数必须提供,实现动画过程中的属性变化。           
door.setRotationY(-120 * Math.PI / 180 * t);       
}   
});
}

The "reset" function here It is the function of "resetting" back to the original point. We use this function to restore all changes to the original position, including the position of the "door":

function reset()
{   
if (window.isAnimationRunning)
{       
return;   
}   
g3d.setCenter([0,0,0]);   
g3d.setEye([523, 5600, 8165]);    window.forwardIndex = 0;  
 door.setRotationY(0);}

To "move", you definitely need to walk" Path", which is the "path" we just obtained, obtain all elements in "path" through window.points = path.getPoints()._as; and initialize window.forwardIndex = 0; by controlling the front and back of "path" Use two points to set the Eye and Center in the 3D scene, so as to create an effect that we are the first person

var point1 = points[forwardIndex],   
 point2 = points[forwardIndex + 1];var distanceX = (point2.x - point1.x),    
distanceY = (point2.y - point1.y),    
distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY)-200;//两点之间的距离通过三角形勾股定理计算 怕碰墙所以-200g3d.setEye([point1.x, 1600, point1.y]);//眼睛g3d.setCenter([point2.x, 1600, point2.y]);//我

The 3D component in HT has a walk(step, anim, firstPersonMode) method. This function simultaneously Change the positions of eye and center, that is, eye and center move at the same time by the same offset in the vector direction established by the two points. step is the offset vector length value. When the firstPersonMode parameter is empty, the current value of Graph3dView#isFirstPersonMode() is used by default. If the walk operation is called for the first-person mode, this function will consider the boundary restrictions of Graph3dView#getBoundaries().

g3d.walk(distance, {   
frames: 50,   
interval: 30,   
easing: function(t) {return t; },   
finishFunc: function() {       
forwardIndex += 1;       
if (points.length - 2 > forwardIndex) {//points.length = 5            g3d.setCenter([point2.x, 1600, point2.y]);//把结束点变成起始点           
g3d.rotate(Math.PI / 2, 0, {              
 frames: 30,             
  interval: 30,              
 easing: function(t) {return t;},                finishFunc:function() { forward();}          
 });     
  }
else
{           
var lastPoint = points[points.length  - 1];//json 中path的points 的最后一个点          
 g3d.setCenter([lastPoint.x, 1400, lastPoint.y]);           
g3d.rotate(-Math.PI / 2, 0,
{              
 frames: 30,              
 interval: 30,              
 finishFunc: function()
{                   
window.isAnimationRunning = false;              
 }          
 });      
 }   
}});

不管“path”的点有多少个,这个判断语句还是能运作,只在最后一个点是跳出 finishFunc 动画结束后调用的函数,并将 window.isAnimationRunning 值设为 false 停止 startAnim 函数。如果不是最后一个点,用户“旋转”之后,回调 forward 函数。至此,全部代码解释完毕,很短的代码量,却做出了这么大的工程!

相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

相关阅读:

手机端怎样用rem+scss做适配

canvas如何实现github404动态

The above is the detailed content of How to use H5's WebGL to implement roaming animation in 3D virtual computer room. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn