用到了高中的一些数学知识,余弦定理,相似三角形,具体解释很繁琐,看不懂就直接复制粘贴吧。
第一次写博客,见笑。
/**
*
* @ author:Lamb90
* @ email:673085601@qq.com
* @ data: 2020-04-22 16:08
*/
export default class CatBall extends Laya.Script {
private catBall:Laya.Sprite;//挂载的物体
private rayCircle;//绘制圆点的载体
constructor() {
super();
}
onAwake() {
this.catBall=this.owner as Laya.Sprite;
Laya.stage.on(Laya.Event.MOUSE_DOWN,this,this.onDown)
}
onDown(){
this.rayCircle=new Laya.Sprite()
Laya.stage.addChild(this.rayCircle)//先添加一个空的到场景避免报错
this.drawLine()
Laya.stage.on(Laya.Event.MOUSE_MOVE,this,this.onMove)
Laya.stage.on(Laya.Event.MOUSE_UP,this,this.onUP);
}
onMove(){
this.drawLine()
}
onUP(){
Laya.stage.off(Laya.Event.MOUSE_MOVE,this,this.onMove);
Laya.stage.off(Laya.Event.MOUSE_UP,this,this.onUP);
this.rayCircle.removeSelf();
}
drawLine(){
this.rayCircle.removeSelf()//清除旧的线
this.rayCircle=new Laya.Sprite();
let dis_x=Laya.stage.mouseX-this.catBall.x
let dis_y=Laya.stage.mouseY-this.catBall.y
let scale;
let x_1;//目标x坐标
if(dis_x>0){
//鼠标在球右边
x_1=0;
scale=dis_x/Laya.stage.mouseX;
}else{
//鼠标在球左边
x_1=Laya.stage.width;
scale=dis_x/(Laya.stage.mouseX-Laya.stage.width);
}
let y_1=this.catBall.y-(dis_y/scale-dis_y);//目标y坐标
//计算长度以确定循环画圈的次数
let disX=x_1-Laya.stage.mouseX;
let disY=y_1-Laya.stage.mouseY;
let length = Math.sqrt(disX*disX+disY*disY)
let num=length/50;//根据需求调整间隔
if(num>50){
num=50//限制绘制次数,防止卡死
}
let lenX=(disX)/length*50;
let lenY=(disY)/length*50;
for(let i=0;i<num;i++){
this.rayCircle.graphics.drawCircle(Laya.stage.mouseX+lenX*i,Laya.stage.mouseY+lenY*i,10-i*0.1,"#ffffff")//调整第三个参数可以实现圆点由大变小的效果
}
let x_2;
let y_2;
let tan;
let disX_2;
let disY_2;
if(x_1==0){
//如果射到左边界
x_2=Laya.stage.width;
tan=(Laya.stage.mouseY-y_1)/Laya.stage.mouseX;
y_2=y_1-Laya.stage.width*tan;
disX_2=Laya.stage.width;
disY_2=-Laya.stage.width*tan
}
if(x_1==Laya.stage.width){
//如果射到右边界
x_2=0;
tan=(Laya.stage.mouseY-y_1)/(Laya.stage.width-Laya.stage.mouseX);
y_2=y_1-Laya.stage.width*tan;
disX_2=-Laya.stage.width;
disY_2=-Laya.stage.width*tan
}
if(y_1<=0){
//如果射到上边界
if(Laya.stage.mouseX-this.catBall.x>0){
//如果鼠标在球的右边
tan=Laya.stage.mouseX/(Laya.stage.mouseY-y_1)
x_1=Laya.stage.mouseX-Laya.stage.mouseY*tan
x_2=x_1-Laya.stage.height*tan;
disX_2=x_2-x_1;
}else{
//如果鼠标在球的左边
tan=(Laya.stage.width-Laya.stage.mouseX)/(Laya.stage.mouseY-y_1)
x_1=Laya.stage.mouseX+Laya.stage.mouseY*tan
x_2=x_1-Laya.stage.height*tan;
disX_2=x_1-x_2;
}
y_1=0;
y_2=Laya.stage.height;
disY_2=y_2-y_1;
}
let lenX_2=disX_2/20;
let lenY_2=disY_2/20;
for(let i=0;i<10;i++){
this.rayCircle.graphics.drawCircle(x_1+lenX_2*i,y_1+lenY_2*i,8-i*0.1,"#ffffff")
}
Laya.stage.addChild(this.rayCircle)
}
}
QQ截图20200423143301.png
把脚本挂在球上面就能自动运行。
网友评论