一,实现功能
在画布中放一个豌豆射手,并制作缩放动作,使每一次缩放结束都发射一颗豌豆。
豌豆射手发射子弹的方向会随鼠标点击的位置而改变,也会随鼠标移动的位置而改变,豌豆也随之改变。
二,应用技术
1.获得画布的鼠标点击坐标,和节点坐标
2.使用预置资源,调用预置资源,
3.使用Math函数获得两坐标之间的偏移弧度,得到主要参数更新射手的方向,并传参到子弹的脚本是子弹也随之更改方向。
4.子弹移动速度是不变的,所以要根据得到的参数改变x y 方向的速度,应用三角函数使的朝目标方向的速度一致。
5.制作射手缩放的动画,应用动画中的2D坐标函数 scale 【调节缩放比例】,并在动画的结尾执行帧函数,所以要为动画添加一个脚本,在帧函数中调用生成子弹的方法,并传参弧度。
6.当子弹移动到画布外的时候要销毁此节点,需要判断什么情况下销毁。
三,代码
游戏脚本
cc.Class({
extends: cc.Component,
properties: {
wanDouPrefab:cc.Prefab,
player:cc.Node,
sheshou:cc.Animation,
},
onLoad () {
this.isFire = false;
},
start () {
let self = this;
this.node.on(cc.Node.EventType.TOUCH_START,function(event){
if (!self.isFire) {
self.isFire = true;
// 执行角色的动画,
self.player.getComponent(cc.Animation).play("sheshou");
}
var touches = event.getTouches();
var touchPos = self.player.parent.convertToNodeSpaceAR(touches[0].getLocation());
var tPos = self.player.position;
var x = touchPos.x - tPos.x;
var y = touchPos.y - tPos.y;
// 获取偏移弧度
var angle = Math.atan2(y, x) * 180 / Math.PI;
let mAngle = 90 - angle;
// 使角色随位置变化方向
self.player.rotation = mAngle;
})
// 鼠标按住滑动
this.node.on(cc.Node.EventType.TOUCH_MOVE,function(event){
var touches = event.getTouches();
var touchPos = self.player.parent.convertToNodeSpaceAR(touches[0].getLocation());
var tPos = self.player.position;
var x = touchPos.x - tPos.x;
var y = touchPos.y - tPos.y;
// 获取偏移弧度
var angle = Math.atan2(y, x) * 180 / Math.PI;
let mAngle = 90 - angle;
// 使角色随位置变化方向
self.player.rotation = mAngle;
})
},
createButtle(mAngle){
// 产生新豌豆
var newDou = cc.instantiate(this.wanDouPrefab);
// 将这个节点添加到这个节点的父节点中
newDou.parent = this.node;
newDou.position = cc.v2(0,-280);
newDou.getComponent("wandou").setAngle(mAngle);
},
// update (dt) {
// },
});
子弹脚本
cc.Class({
extends: cc.Component,
properties: {
wandou: {
default: null,
type: cc.Node
},
},
// onLoad () {},
start () {
},
setAngle(mAngle){
this.wandou.rotation = mAngle;
console.log(mAngle)
},
update (dt) {
// 更新豌豆位置
this.wandou.x += 10*Math.sin(this.wandou.rotation* Math.PI/180)
this.wandou.y += 10*Math.cos(this.wandou.rotation* Math.PI/180)
if(this.wandou.x>640 || this.wandou.x<-640 || this.wandou.y > 360){
this.wandou.destroy()
console.log("已销毁")
}
},
});
动画脚本
// 动画帧函数绑定
fire(){
// 查到到画布下的游戏脚本,脚本中的创建子弹的方法,并将弧度做参数传入
cc.find("Canvas").getComponent("game").createButtle(this.node.rotation);
},
结语
为自己的每天负责,坚持你要做的事情
大家好,我是一只弱小的程序员,希望大家给我鼓励。让我坚持做下去。