Hello!
I wonder how to do draggable sprite in CocosBuilder. Does anyone know how?
In pure javascript I did it this way:
var STATE_GRABBED = 0;
var STATE_UNGRABBED = 1;
var kShipXSize = 60;
var kShipYSize = 40;
var Ship = cc.Sprite.extend({
_x : 0,
_y : 0,
_state : STATE_UNGRABBED,
_parked : false,
_rect:null,
rect:function () {
return cc.rect(-this._rect.size.width / 2, -this._rect.size.height / 2, this._rect.size.width, this._rect.size.height);
},
ctor : function() {
var img = cc.TextureCache.getInstance().addImage(p_texturePack);
this.initWithTexture(img, cc.rect(405, 0, 68, 40));
},
onEnter : function() {
cc.Director.getInstance().getTouchDispatcher().addTargetedDelegate(this, 0, true);
this._rect = cc.rect(405, 0, 68, 40);
this._super();
},
onExit : function() {
cc.Director.getInstance().getTouchDispatcher().removeDelegate(this);
this._super();
},
containsTouchLocation : function(touch) {
var getPoint = touch.getLocation();
var myRect = this.rect();
myRect.origin.x += this.getPosition().x;
myRect.origin.y += this.getPosition().y;
return cc.Rect.CCRectContainsPoint(myRect, getPoint);// this.convertTouchToNodeSpaceAR(touch));
},
onTouchBegan : function(touch, event) {
if (this._state != STATE_UNGRABBED)
return false;
if (!this.containsTouchLocation(touch))
return false;
this._state = STATE_GRABBED;
return true;
},
onTouchMoved : function(touch, event) {
cc.Assert(this._state == STATE_GRABBED, "Paddle - Unexpected state!");
cc.Assert(this._parked == false, "Paddle - Unexpected state!");
if (!this._parked) {
var touchPoint = touch.getLocation();
this.setPosition(cc.p(touchPoint.x, touchPoint.y));
}
},
onTouchEnded : function(touch, event) {
cc.Assert(this._state == STATE_GRABBED, "Paddle - Unexpected state!");
this._state = STATE_UNGRABBED;
},
});
I tried with connecting that js file with my sprite in CocosBuilder, but it does not even detect touches:
var Krzyzak = function()
{
};
Krzyzak.prototype.onDidLoadFromCCB = function()
{
cc.log("START");
this.rootNode.onTouchesBegan = function( touches, event) {
this.controller.onTouchesBegan(touches, event);
return true;
};
};
Krzyzak.prototype.onTouchesBegan = function(touches, event)
{
var loc = touches[0].getLocation();
cc.log(">>>>> LOCATION: "+loc);
};