1.效果
2.原理
残影与小地图原理是应用camera的属性targetTexture实现的,因为targetTexture是指定摄像机将拍摄到的东西渲染到指定的 RenderTexture上面,通过对指定的RenderTexture进行特殊处理来达到残影的效果。这么做的好处是如果我想要很多东西出现残影、只需要创建出残影的一组图片就能对多个物体进行统一的残影显示。
3代码
const {ccclass, property} = cc._decorator;
@ccclass
export default class MoveShadow extends cc.Component {
@property(cc.Sprite)
shadow_sprite: cc.Sprite = null;
@property(cc.Camera)
shadow_camera: cc.Camera = null;
@property(cc.Node)
shadowNode: cc.Node =null;
@property(cc.Node)
private canvas_node:cc.Node = null;
@property(cc.Sprite)
private map_spirte:cc.Sprite = null;
@property(cc.Camera)
private map_Camera:cc.Camera = null;
start () {
this.schedule(this.moveShadow,0.1,cc.macro.REPEAT_FOREVER);
this.shadow_sprite.node.on(cc.Node.EventType.TOUCH_MOVE,this.heroMove,this);
//创建一个RenderTexture
let renderTexture = new cc.RenderTexture();
//初始化大小
renderTexture.initWithSize(this.canvas_node.width,this.canvas_node.height);
//创建一个SpriteFrame
let spriteFrame = new cc.SpriteFrame();
spriteFrame.setTexture(renderTexture);
//设置camera将渲染的内容制定到新建的RenderTexture
this.shadow_camera.targetTexture = renderTexture;
//将新建的SpriteFrame设置给显示残影的图片
this.shadowNode.children.map((item,index)=>{
index = this.shadowNode.childrenCount - index - 1;
//由于坐标系的问题 需要将y轴进行反转
item.scaleY = -1;
item.opacity = 200 - 30*index;
item.getComponent(cc.Sprite).spriteFrame = spriteFrame;
});
//小地图原来一样
let texture_map = new cc.RenderTexture();
texture_map.initWithSize(this.map_spirte.node.width,this.map_spirte.node.height);
let sf_map = new cc.SpriteFrame();
sf_map.setTexture(texture_map);
this.map_Camera.targetTexture = texture_map;
this.map_spirte.node.scaleY = -1;
this.map_spirte.spriteFrame = sf_map;
cc.tween(this.shadow_sprite.node).repeatForever(cc.tween().to(3,{angle:180}).to(3,{angle:0})).start();
}
onDestroy(){
this.unschedule(this.moveShadow);
}
private heroMove(event:cc.Event.EventTouch){
this.shadow_sprite.node.setPosition(this.node.convertToNodeSpaceAR(event.getLocation()));
}
/**
* 移动动画
*/
private moveShadow(){
this.shadowNode.children.map((item,index)=>{
index = this.shadowNode.childrenCount - index - 1;
let targetPos = this.shadow_sprite.node.position;
if(item.position.sub(targetPos).mag()<0.5){
return;
}
item.stopAllActions();
item.runAction(cc.moveTo(index*0.1+0.2,new cc.Vec2(targetPos.x,targetPos.y)));
});
}
}