The broken mirror of the Xu family is as dim as fog. Half of the face is exposed. We meet casually to watch the lights. Unexpectedly, the sky on earth is like a shooting star. The shadow of the red door curtain is deep in the rain. The haggard newcomer dances. Enjoy the new sunshine from all over the world. Only selling mirrors by the bridge is a leisurely activity.
——Song Dynasty Liu Chenweng·"Poppy"
When shooting stars appear, people like to make wishes on them, because it is said that if you make a wish on the shooting stars, the wish will come true. But shooting stars are rare, at least I haven't seen them, so I have never made a wish on them. Recently, out of interest, I created a trailing effect, and then I thought that I could use the trailing effect to achieve the effect of a meteor shower. So let’s do it today, so that children like me who have never seen a shooting star will gain some insights.
Let me post a few screenshots first:
Test the connection: http://www.cnblogs.com/yorhom/articles/3237944.html
1. Preparation
This development requires the open source engine lufylegend.js. The download address and details of the engine are as follows
Official website of the engine:
http://lufylegend. com/lufylegend
Engine API website:
http://lufylegend.com/lufylegend/api
2. Trailing effect
To realize the meteor shower, you need to use the trailing effect , but there is no tailing function in lufylegend, so I had to write it myself. In fact, it is not difficult to implement, but lufy is too lazy and has no encapsulation (I hope lufy will not see this sentence...). Today I will help him achieve this effect.
The tailing effect is very common in games, such as phantoms and bullets when characters move. Therefore, we encapsulate it as a Smearing class, which is mainly responsible for achieving the trailing effect. The code is as follows:
/**
* Smearing
* @param $object Add trailing object
*/
function Smearing($object){
var self = this;
base(self,LSprite,[]);
self.x = 0;
self.y = 0 ;
self.mode = "";
self.smearingSprite = new LSprite();
self.addChild(self.smearingSprite);
self.object = $object;
self. originalSprite = new LSprite();
self.addChild(self.originalSprite);
self.originalSprite.addChild(self.object);
self.addEventListener(LEvent.ENTER_FRAME,self.smeared);
}
Code Listing 1
Let me explain it word for word.
I won’t explain the first line of code, every IT person on earth knows it. So start with the second line.
First, we inherit this class from LSprite using base, as shown in code listing 2 (as for what base and LSprite are, you can check it out in the API documentation, or read my previous articles).
base(self,LSprite,[]) ;
Code Listing 2
Next, we add a layer to add a trail. For example, code listing 3
self.smearingSprite = new LSprite();
self.addChild(self.smearingSprite);
Code Listing 3
Then we save the object with the trailing effect, so that it can be used later. As shown in code listing 4
self.object = $object;
Code Listing 4
Then add a layer where you want to add the trailing effect object and display it. For example, code listing 5
self.originalSprite = new LSprite();
self.addChild(self.originalSprite);
self.originalSprite.addChild(self.object);
Code Listing 5
Finally add a timeline Event, convenient for adding tail.
self.addEventListener(LEvent.ENTER_FRAME,self .smeared);
Code List 6
At this point, the Smearing constructor has been written and explained. If you don’t understand it, maybe you don’t understand lufylegend. The addChild and LSprite inside are all encapsulated in lufylegend.
We have added timeline events to the above code. Why join? Because I might as well talk about the principle of tailing. Trailing is actually to continuously clone the original object and then place it at its current location, which is equivalent to constantly stamping the screen. When the original object moves away, the object we clone does not move away, but the original object moves away. If we add many objects, a line will be formed connecting the original object. At this time, we will traverse each member of this line and change the transparency of the current object through easing. Then determine whether the transparency of the object is 0, and if so, remove it to avoid taking up too much space. Therefore, we add timeline events to continuously add trailing objects.
Smearing member function smeared plays this role, the code is as follows:
Smearing.prototype.smeared = function(self){
var smearingChild = new SmearingChild(self.originalSprite,self.object);
self.smearingSprite.addChild(smearingChild);
for(var key in self.smearingSprite.childList){
LTweenLite.to(self.smearingSprite.childList[key],0.5,{
alpha: 0,
onComplete:function(o){
self.smearingSprite.removeChild(o);
}
});
}
};
Code Listing 7
These codes are as follows: The principle mentioned above is implemented. You can see that we traverse the members of the trailing layer at the end, then change the transparency of the traversed object, and remove itself after the easing ends. The easing class uses LTweenLite encapsulated in lufylegend. You can check it out in the API documentation, which is very detailed.
Mainly the above two lines of code, such as code listing 8:
var smearingChild = new SmearingChild(self.originalSprite,self.object);
self.smearingSprite.addChild(smearingChild);
Code Listing 8
You can see Another class called SmearingChild is used. This is the legendary tailing class. This class cannot be ignored. Although the code is small, it is very important. The code inside is as shown in code listing 9:
/**
* SmearingChild
* @param $parent The object to determine the trailing position
* @param $object The object to add the trailing effect
*/
function SmearingChild($parent,$object){
var self = this;
base(self,LSprite ,[]);
self.addChild($object);
self.x = $parent.x;
self.y = $parent.y;
self.alpha = 0.8;
}
Code Listing 9
The above class has two parameters when instantiated. The first one is used to determine the trailing position, and the second one is the original object. First, let’s explain what “used to determine the trailing position” means. In fact, the movement of our object is not to move the entire Smearing object, but to move the originalSprite object inside it, so we don’t do the smearingSprite thing. Why? What about this design? In fact, there is a reason (nonsense, please ignore it). The reason is that if the coordinates of our tail are set to the coordinate position of the entire Smearing object, then the object added to the smearingSprite will also move accordingly, and the tail will be misaligned, thus achieving No effect. So I took the above approach: not moving itself, but moving the originalSprite. Therefore, we need to pass the originalSprite data to SmearingChild, so we get it through $parent.
After talking about it, everyone should understand a little bit. The code will be released later, and you can take it and study it, or ask questions below the article or use Sina Weibo @Yorhom, or use email address: wangyuehao1999@gmail.com. (There are many contact information (^o^))
The Smearing class still lacks one function, which is to make the object move slowly. It is also very simple to implement. Add the to function:
Smearing.prototype.to = function($duration,$vars){
var self = this;
$vars.onComplete = function(){
self.mode = "complete";
}
LTweenLite.to(self.originalSprite,$duration,$vars);
};
코드 목록 10
첫 번째 매개변수는 이동 실행 시간, 두 번째 매개변수는 완화 실행 데이터로 LTweenLite.to 메소드의 마지막 매개변수와 동일합니다. API 문서를 참조하세요. 그러나 작업의 편의를 위해 이동이 끝나면 개체의 모드 속성을 "완료"로 변경한다는 점은 주목할 가치가 있습니다. 이는 모든 사람이 객체 제거 또는 다른 곳으로 이동과 같은 모드 속성의 값을 기반으로 다른 작업을 수행할지 여부를 결정할 수 있도록 수행됩니다.
Smearing 클래스는 다음과 같이 캡슐화되어 사용하기 쉽습니다.
init(10,"mylegend",500,400,main)
var back
function main(){
LStage.setDebug(true); 🎜>back = new LSprite();
back.graphics.drawRect(0,"",[0,0,50,50],true,"blue")
smearing = new Smearing(back, 50);
smearing.to(2,{
x: 200,
y: 200
})
addChild(smearing)
코드 목록 11
데모 렌더링은 다음과 같습니다.
테스트 연결: http://www.cnblogs.com/yorhom/articles/3237266.html
셋, 눈부신 유성우 효과
Smearing 클래스를 이용하면 유성우가 훨씬 간편해집니다. 먼저 모든 코드를 보여주세요:
init( 10,"mylegend",500,400,main);
var backLayer,meteorLayer;
var back,meteor;
var maxFrame = 40,indexFrame = 0; {
LStage.setDebug(true);
//기본 레이어 추가
backLayer = new LSprite();
addChild(backLayer)
//유성 레이어 추가
meteorLayer = new LSprite() ;
addChild(meteorLayer);
//배경으로 검은색 직사각형 그리기
back = new LGraphics()
back.drawRect(0,"",[0, 0,LStage.width ,LStage.height],true,"black");
backLayer.addChild(back);
//유성으로 노란색 직사각형 그리기
meteor = new LSprite();
meteor .graphics.drawRect(0,"",[0,0,10,10],true,"yellow")
backLayer.addEventListener(LEvent.ENTER_FRAME,onframe)
}
function onframe (){
if(indexFrame > maxFrame){
indexFrame = 0
//각 유성에 꼬리 추가
var smearing = new Smearing(meteor,50);
smearing.x = Math.floor(Math.random() * 250);
smearing.y = 0;
smearing.to(2,{
x: Math.floor(Math. 무작위( ) * (500 - 480) 480),
y: 400
})
meteorLayer.addChild(smearing)
}
for(meteorLayer.childList의 var 키) {
if(meteorLayer.childList[key].mode == "complete"){
meteorLayer.removeChild(meteorLayer.childList[key])
}
}
indexFrame; 🎜> }
코드 목록 12
코드의 각 줄마다 주석이 추가되므로 매우 이해하기 쉬워야 합니다. 정말 이해할 수 없다면 루피전설을 이해하지 못해서일 수도 있습니다. 자세한 내용은 API 설명서를 참조하세요.
마지막 단계는 코드 패키징,
주소 다운로드
이 글은 여기서 끝납니다. 글에 부적절한 내용이 있으면 지적해 주시기 바랍니다. 또한, 궁금하신 점은 블로그 아래에 메시지를 남겨주시면 해결하도록 최선을 다해 도와드리겠습니다.
지원은 최고의 격려입니다!