场景布置
游戏资源
炮塔旋转
机制与之前手柄实例的小车相同,使用touchmove监听触摸事件,
- 获取触摸位置
- 通过位置用signAngle方法将该位置与cc.v2(1,0)位置的角度差求出(记得要加负号,比较所得逆时针为负,赋值angle逆指针为正)。
- 所求的的角度即为最终角度。
onLoad(){
//初始化为90度
this.node.angle=90;
this.node.on('touchstart',this.onTouchStart,this);
this.node.on('touchmove',this.onTouchMove,this);
this.node.on('touchend',this.onTouchEnd,this);
this.node.on('touchconcel',this.onTouchConcel,this);
}
onTouchStart(e:cc.Event.EventTouch){
//获取开始的位置
this.starPos=this.node.parent.convertToNodeSpace(e.getLocation());
//获取炮口的初始角度
this.starAngle=this.node.angle;
}
onTouchEnd(e:cc.Event.EventTouch){
}
onTouchMove(e:cc.Event.EventTouch){
//获取触点当前的位置
let pos:cc.Vec2=this.node.parent.convertToNodeSpace(e.getLocation());
//获取角度
//angle顺时针为负逆时针为正
let sweep_radian=pos.signAngle(this.starPos);//pos相对于starPose的角度p相对s顺时针为正
let sweep_angle=sweep_radian*180/Math.PI;//弧度制换算角度
//让炮塔的角度指向最终的角度
let angle=this.starAngle-sweep_angle;
//将角度限制在45~135之间
if(angle<45)angle=45;
if(angle>135)angle=135;
cc.log("炮口摆动:"+sweep_angle+"最终角度位置:"+angle);
this.node.angle=angle;
}
动态生成子弹
- 生成节点cc.Node,并增加组件addComponent(cc.Sprite)
- 为组件的属性赋值,将图片的spriteFrame赋值
- 将组件挂载在一个父节点下
- 设置位置、角度等
- 控制其运动可以导入新建的脚本,并将该脚本增加到动态生成节点的组件中
onTouchEnd(e:cc.Event.EventTouch){
this.fire();
}
onTouchConcel(e:cc.Event.EventTouch){
}
fire(){
if(this.bulleteicon==null)return;
let bullet:cc.Node=new cc.Node();
let sprite:cc.Sprite=bullet.addComponent(cc.Sprite);
sprite.spriteFrame=this.bulleteicon;
//挂载到射击系统节点下
bullet.parent=this.node.parent;
//设置相对父节点位置
let ration=this.node.angle*Math.PI/180;
let direction=cc.v2(Math.cos(ration),Math.sin(ration));
bullet.angle=this.node.angle;
let r=100;
bullet.setPosition(cc.v3(r*direction.x,r*direction.y,0));
//附加脚本组件