这里涉及一些基本的三角知识,为了后面的向量,转向行为打下基础
var HelloWorldLayer = cc.Layer.extend({
arrow:null,//测试用箭头
angle:null,
speed:5,
ctor:function () {
this._super();
var winsize = cc.director.getWinSize();
this.arrow = new Arrow();
this.addChild(this.arrow,0);
this.arrow.attr({
x:winsize.width/2,
y:winsize.height/2
});
this.init();
return true;
},
init:function(){
var that = this;
cc.eventManager.addListener({
prevTouchId: -1,
event: cc.EventListener.TOUCH_ONE_BY_ONE,
onTouchBegan:function (touch, event) {
return true;
},
onTouchMoved:function(touch,event){
var tPos = touch.getLocation();
var dx = tPos.x - that.arrow.x;
var dy = tPos.y - that.arrow.y;
that.angle = Math.atan2(dy, dx);
//弧度转角度,由于Cocos2d中顺时针是正的角度,而三角函数中x轴正向为正的角度,所以加个负号来修正
that.arrow.rotation = -that.angle*180/Math.PI;
return true;
},
onTouchEnded:function (touch, event) {
return true;
},
}, this);
this.scheduleUpdate();
},
update:function(){
var vx = Math.cos(this.angle)*this.speed;
var vy = Math.sin(this.angle)*this.speed;
this.arrow.x += vx;
this.arrow.y += vy;
}
});
var HelloWorldScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new HelloWorldLayer();
this.addChild(layer);
}
});