1. 程式人生 > >cocos creator 判斷某點是否在某個rect內部

cocos creator 判斷某點是否在某個rect內部

先放官方文件:

var a = new cc.Rect(0, 0, 10, 10);
var b = new cc.Vec2(0, 5);
a.contains(b);// true

rect的獲取:

// 世界座標
this.node.getBoundingBoxToWorld();
// 區域性座標
this.node.getBoundingBox();

觸點的獲取:

///監聽玩家操控
    setTouchListener:function(){
        var self = this;
        var listener = {
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            onTouchBegan: function (touches, event) {
                var target = event.getCurrentTarget();//獲取事件所繫結的target
                var locationInNode = target.convertToNodeSpace(touches.getLocation());

                if(locationInNode.x>self.node.width/2){
                    cc.log("touches:" + touches.getLocation().x);
                    cc.log("座標: " + locationInNode.x + " 大於 " + self.node.width/2);
                   cc.log("點選螢幕右側");
                }else{
                    cc.log("座標: " + locationInNode.x + " 小於 " + self.node.width/2);
                    cc.log("點選螢幕左側");
                }
                return true; //這裡必須要寫 return true
            },
            onTouchMoved: function (touches, event) {
              
            },
            onTouchEnded: function (touches, event) {
           
            },
            onTouchCancelled: function (touches, event) {
            }
        }
        cc.eventManager.addListener(listener, self.node);
    },