子弹跟踪实现 (极简版)

总体逻辑:开始觉得可以用缓动动画去实现,但是 有一个问题就是子弹跟踪的 目标位置是实时变化的,终点和角度 不可预料, 所以可行的方法 就是在 子弹的update里 每帧检测 目标的位置 ,实时更新子弹的位置和角度。

主要代码: 事实上只要 控制子弹的 位置和角度就可以了,关键是update处理函数
init(plane){ this.plane = plane; this.setSpeed(150); } ​ update (dt) { if(this.plane){ let targetPos = this.plane.position; let pos = this.node.position; ​ //算出目标与子弹的向量差 let delta = targetPos.sub(pos); ​ //算出向量长度 let distance = pos.sub(targetPos).mag(); ​ //计算该帧子弹的位置 let x2 = pos.x + dt* this.speed * delta.x / distance; let y2 = pos.y + dt* this.speed * delta.y / distance; let x1 = pos.x; let y1 = pos.y; ​ //计算弧度 let radian = Math.atan2(y2 - y1, x2 - x1) ​ //弧度转角度 let angle = radian * 180 / Math.PI - 90 ; this.node.angle = angle; ​ this.node.position = cc.v3(x2,y2); ​ let rect = this.plane.getBoundingBox(); if(rect.contains(cc.v2( this.node.position.x, this.node.position.y))){ console.log("hit"); this.node.destroy(); } } } ​ setSpeed(speed:number){ this.speed = speed; }
效果如下:

点击下方二维码关注公众号 发送 genzong 获取完整代码

2赞