Search code examples
javascriptcocos2d-js

How to use mouse event for adding sprite Cocos2d-js


I'm already trying but it's not what I'm expecting.

I want create something when my mouse pointing a sprite, that sprite glowing or have red border or something notice you that mouse pointing that sprite. in this case I'm calling another sprite with same sprite but more brighter.

it's not really a sprite, I have background like a sprite i want, so here the code pointing specific location from my background

Objs.aSprite_1st12 = new cc.Node();
Objs.aSprite_1st12.setContentSize(100,100);
Objs.aSprite_1st12.setAnchorPoint(0.5, 0.5);
Objs.aSprite_1st12.setScaleX(1.4);
Objs.aSprite_1st12.setScaleY(0.4);
Objs.aSprite_1st12.setRotation(25);
Objs.aSprite_1st12.setSkewX(10);
Objs.aSprite_1st12.setSkewY(-12);
Objs.aSprite_1st12.setPosition(cc.p(474,263));
this.addChild(Objs.aSprite_1st12, 10);

and i'm calling function mouse event

mouseEvent(this);

here the function is

function mouseEvent(that){
cc.eventManager.addListener({
        event:cc.EventListener.MOUSE,
        onMouseMove: function (event){
            var target = event.getCurrentTarget();
            var locationInNode = Objs.aSprite_1st12;
            var s = target.getContentSize();
            var rect = cc.rect(0, 0, s.width, s.height);
            if (cc.rectContainsPoint(rect, locationInNode)) {
                var sprite1 = new cc.Sprite.create(Objs.sidechip);
                sprite1.setPosition(cc.p(474,263));
                sprite1.setScale(0.3);
                that.addChild(sprite1,0);
            }
        }
    }, that);
}

this code working, and a new sprite added in specific location I want it when the mouse is moving, but the problem is whenever the mouse move that sprite always added. i just want if that mouse pointing Objs.aSprite_1st12, new sprite added.


Solution

  • here the code exactly what i want it.

    var sprite1 = new cc.Sprite.create(Objs.sidechip);
                            sprite1.setPosition(cc.p(474,263));
                            sprite1.setScale(0.3);
                            sprite1.setVisible (false);
                            this.addChild(sprite1,0);
        cc.eventManager.addListener(
        {
            event:cc.EventListener.MOUSE,
    
            onMouseMove: function (event)
            {
                var n = Math.floor(event.getLocationX());
                var m = Math.floor(event.getLocationY());
                if (n >= 396 && n <= 556 && m >= 216 && m <= 303){
                cc.log ("ikeh");    
                sprite1.setVisible (true);
                }else{
                    sprite1.setVisible (false);
                }
            }
        }, this);
    

    so I just add the sprite I want it first and setVisible(false); then, when mouse pointed between (n >= 396 && n <= 556 && m >= 216 && m <= 303) it's setVisible(true);.