首先定义一个cocosCreator的cc.Graphics组件,作为敌人视野的渲染画线和填充组件:
//画线组件
g:cc.Graphics;
//敌人视野半径的角度大小
emenyAngle:number=45;
//巡逻半径的大小
distance:number=450;
然后在update或者其它定时器每帧频率里边写下渲染画线的方法:
//每帧调用
update(){
if(this.g= =null){
this.g=this.node.addComponent(cc.Graphics);
}
this.g.clear();
this.g.moveTo(0,0);
let suess=false;
//获取点集合
for(let i=this.emenyAngle;i>(0-this.emenyAngle);i--){
i=i-3;
let v1= new cc.Vec2(Math.sin(Math.PI * i / 180)*this.distance,-Math.cos(Math.PI * i / 180)*this.distance);
//当前目标点的场景坐标
let v2=this.node.convertToWorldSpaceAR(v1);
let results=cc.director.getPhysicsManager().rayCast(new cc.Vec2(this.node.position.x,this.node.position.y),v2,cc.RayCastType.All);
for(let j=0;j<results.length;j++){
if(results[j].collider.node.group=="map"&&results[j].collider.tag= =0){
let v3=this.node.convertToNodeSpaceAR(results[j].point);
if(Math.sqrt(Math.pow(0 - v3.x , 2 )+ Math.pow(-30- v3.y , 2 ))<Math.sqrt(Math.pow(0 - v1.x , 2 )+ Math.pow(-30 - v1.y , 2 ))){
v1= this.node.convertToNodeSpaceAR(results[j].point);
}
}
//当视野出现英雄 调用射线检测
if(results[j].collider.node.group=="hero"){
this.ray();
suess=true;
}
//当视野内出现敌人,判断是否死亡
if(results[j].collider.node.group=="emeny"){
if(this.xunluomove&& results[j].collider.node.parent.getComponent(emenyLevel).death==true){
this.rayToFriendsDeath(results[j].collider.node.parent.position);
suess=true;
}
}
}
this.g.lineTo(v1.x,v1.y);
}
if(suess){
if(Math.sqrt(Math.pow(this.node.x - this.socker.position.x , 2 )+ Math.pow( this.node.y - this.socker.position.y , 2 ))<60){
//敌人追击到主角
this.gameOver=true;
this.xunluomove=false;
this.findOut=false;
//游戏暂停
Allcontrol.instance.suspend=true;
//调用界面
this.GameOver();
}
//this.onViewAll=true;
}
else{
//敌人不在这里插入代码片在视野内
this.onView=false;
//this.onViewAll=false;
}
this.g.lineTo(0,0);
this.g.fillColor = cc.color(0,172,242,100);
this.g.fill();
}
//具体原理就是:在敌人身上限定的角度和视野的距离,然后在每帧遍历敌人身上的指定角度,然后发出从敌人点到指定角度距离点的一个射线,然后返回射线检测的值,找到最近的点,保存,一轮遍历下来,一个角度或者多个角度返回一个点,把点连起来是个多边形,然后填充,就实现了敌人的扇形可随障碍物改变的一个视野。