[cocos 2d WeChat Mini Game Development Tutorial] Basic Note Sharing (1)

  1. Development document address
    https://docs.cocos.com/creator/2.4/manual/zh/

  2. Mount the script
    Right-click to create a new script
    insert image description here
    insert image description here

  3. Script interpretation
    Change the class name and script name to be consistent, insert image description here
    allowing other script calls

    export default 
    

    The value of the panel is used first for text, and it will not be displayed on the panel if the property is removed

    @property//去掉则不在面板上显示
    text: string = 'hello';
    

    printout

    console.debug('调用');
    
  4. Explanation of lifecycle functions

    //初始化调用,第一个被调用
    onLoad () {
          
          
        console.debug('调用');
    }
    //启用脚本调用,在onLoad和start之间执行,会多次调用
    onEnable() {
          
          
        
    }
    //初始化调用,第二个被调用
    start () {
          
          
    
    }
    
    //每帧开始调用,dt执行时间
    update (dt) {
          
          }
    
    //每帧结束调用
    lateUpdate(dt) {
          
          
        
    }
    //禁用脚本调用
    onDisable() {
          
          
        
    }
    
    //销毁时调用
    onDestroy() {
          
          
        
    }
    
  5. use of nodes

    start () {
          
          
        //获取子字节点
        let a = this.node.children[0];
        //根据子节点名称获取节点
        this.node.getChildByName('abc');
        //通过路径查找节点
        cc.find('Canvas/Main Camera')
        //获取父节点
        this.node.getParent();
        //设置一个父节点
        this.node.setParent(a);
        //移除所有子节点
        this.node.removeAllChildren();
        //移除某个节点
        this.node.removeChild(a);
        //从父节点移除掉,我删我自己
        this.node.removeFromParent();
    
        //获取位置
        this.node.x;
        this.node.y
        //设置位置
        this.node.setPosition(3,4);
        this.node.setPosition(cc.v2(3,4));
        //旋转
        this.node.rotation;
        //缩放
        this.node.scale;
        //锚点
        this.node.anchorX;
        //设置颜色
        this.node.color = cc.Color.RED;
    
        //节点开关
        this.node.active = false;
        //组件开关
        this.enabled = false;
    
        //按类型获取组件(填写组件类型)
        let sprite = this.getComponent(cc.Sprite);
        //从子集按类型获取组件
        this.getComponentInChildren(cc.Sprite);
    
    	//创建节点
        let node = new cc.Node("New");
        //添加组件(创建一个精灵组件)
        node.addComponent(cc.Sprite);
    }
    
    
  6. Preset

  • Drag and drop to add presets
    insert image description here

  • Render presets with code Script
    insert image description here
    content

    @ccclass
    export default class Test extends cc.Component {
          
          
    
        @property(cc.Label)
        label: cc.Label = null;
    
        @property//去掉则不在面板上显示
        text: string = 'hello';
    
    	//定义预设体
        @property(cc.Prefab)
        pre:cc.Prefab = null;
    
        // LIFE-CYCLE CALLBACKS:
    
        //初始化调用,第一个被调用
        onLoad () {
          
          
            console.debug('调用');
    
            //实例化预设体
            let node = cc.instantiate(this.pre)
            //设置父节点,不设置父节点不会显示
            node.setParent(this.node);
        }
    }
    
    1. Dynamic loading of resources (belongs to asynchronous loading and does not affect the operation of the main program code)
    • Create a new assets/resource resource file,名称一定不能错
      insert image description here

    • Put the image resource file to be loaded in resources,记得改为精灵类型
      insert image description here

    • Writing scripts for dynamic loading

      start () {
              
              
          var that = this;
          //旧的方式,2.4以上已经不推荐使用,可能之后会废除,不建议使用
          cc.loader.loadRes("test/land", cc.SpriteFrame, function(err, sp:cc.SpriteFrame){
              
              
              that.getComponent(cc.Sprite).spriteFrame = sp;
          });		
           //新版本使用
         	cc.resources.load("test/land", cc.SpriteFrame, function(err, sp:cc.SpriteFrame) {
              
              
              that.getComponent(cc.Sprite).spriteFrame = sp;
          });
      	
      	//加载远程图片
          cc.loader.load({
              
              url:item.avatarUrl,type:'jpg'},function(err,tex){
              
              
               that.getComponent(cc.Sprite).spriteFrame  = new cc.SpriteFrame(tex);
           });
      }
      
      
    • Dynamically load an atlas

      //动态加载某个图集
      cc.resources.load("test/land1", cc.SpriteAtlas, function(err, atlas:cc.SpriteAtlas){
              
              
          that.getComponent(cc.Sprite).spriteFrame = atlas.getSpriteFrame("hero1");
      });
      

      insert image description here

  1. Scenes
  • new scene
    insert image description here

  • ctrl+s save the scene as game1, game2, put it in the assets/scene directory, double-click to open the switch
    insert image description here

  • load scene, switch scene

    //直接切换场景
    cc.director.loadScene("game2", function(){
          
          
       //当前已经加载到新的场景了
    });
    
    //预加载,用在一些比较大的场景时
    cc.director.preloadScene("game2",function(){
          
          
       //这个场景已经加载到内存了,但是还没有用
       cc.director.loadScene("game2");
    })
    
  • Resident nodes, such as the statistics of game play time

    //添加常驻的节点,所有场景都有,换场景也不会销毁,this.node 表示当前节点
    cc.game.addPersistRootNode(this.node);
    
    //移除常驻节点
    cc.game.removePersistRootNode(this.node)
    
  1. mouse events and touch events

    //绑定事件
    this.node.on(cc.Node.EventType.MOUSE_DOWN, function(event){
          
          
       console.debug('鼠标按下啦!!');
       
       //获取当前点击的位置
       event.getLocation()
       event.getLocationX()
       event.getLocationY()
       
       if(event.getButton() == cc.Event.EventMouse.BUTTON_RIGHT){
          
          
           console.debug('点击了鼠标右键!!');
       }
    })
    
    //取消绑定事件
    this.node.off(cc.Node.EventType.MOUSE_DOWN,function(event){
          
          
    	//用法同上
    });
    
    //触摸事件
    this.node.on(cc.Node.EventType.MOUSE_DOWN, function(event){
          
          
        //按触摸id判断有几个手指
        console.debug('触摸' + event.getID());
    })
    

    Mouse events are only triggered on desktop platforms. The event types provided by the system are as follows:

    enum object definition corresponding event name When the event is triggered
    cc.Node.EventType.MOUSE_DOWN ‘mousedown’ Triggered once when the mouse is pressed on the target node area
    cc.Node.EventType.MOUSE_ENTER ‘mouseenter’ When the mouse moves into the target node area, regardless of whether it is pressed
    cc.Node.EventType.MOUSE_MOVE ‘mousemove’ When the mouse moves in the target node area, whether it is pressed or not
    cc.Node.EventType.MOUSE_LEAVE ‘mouseleave’ When the mouse moves out of the target node area, regardless of whether it is pressed
    cc.Node.EventType.MOUSE_UP ‘mouseup’ Fired once when the mouse is released from the pressed state
    cc.Node.EventType.MOUSE_WHEEL ‘mousewheel’ when the mouse wheel scrolls

    The important APIs of the mouse event (cc.Event.EventMouse) are as follows (beyond the cc.Event standard event API):

    Function name return type significance
    getScrollY Number Get the Y-axis distance of the scroll wheel, it is only valid when scrolling
    getLocation Object Get the mouse position object, the object contains x and y properties
    getLocationX Number Get the X-axis position of the mouse
    getLocationY Number Get the Y-axis position of the mouse
    getPreviousLocation Object Get the position object when the mouse event was triggered last time, the object contains x and y properties
    getParticipate Object Get the distance object that the mouse moved from the last event, the object contains x and y attributes
    getButton Number cc.Event.EventMouse.BUTTON_LEFT 或 cc.Event.EventMouse.BUTTON_RIGHT 或 cc.Event.EventMouse.BUTTON_MIDDLE

    Touch event type and event object
    Touch events are triggered on both mobile platforms and desktop platforms. The purpose of this is to better serve developers for debugging on desktop platforms. Only need to monitor touch events to respond to touch events on mobile platforms and desktops at the same time. End mouse events. The types of touch events provided by the system are as follows:

    enum object definition corresponding event name When the event is triggered
    cc.Node.EventType.TOUCH_START ‘touchstart’ When the finger touch falls within the target node area
    cc.Node.EventType.TOUCH_MOVE ‘touchmove’ When the finger moves within the target node area on the screen
    cc.Node.EventType.TOUCH_END ‘touchend’ When the finger leaves the screen within the target node area
    cc.Node.EventType.TOUCH_CANCEL ‘touchcancel’ When the finger leaves the screen outside the target node area

    The important APIs of the touch event (cc.Event.EventTouch) are as follows (beyond the cc.Event standard event API):

    API name type significance
    touch cc.Touch The contact object associated with the current event
    getID Number Get the ID of the touch point for logical judgment of multi-touch
    getLocation Object Get the contact position object, the object contains x and y attributes
    getLocationX Number Get the X-axis position of the touch point
    getLocationY Number Get the Y-axis position of the touch point
    getPreviousLocation Object Get the position object when the last trigger event of the contact, the object contains x and y attributes
    getStartLocation Object Get the initial position object of the contact, the object contains x and y attributes
    getParticipate Object Get the object of the distance moved by the touch point from the last event, the object contains x and y attributes
  2. keyboard events

    /*
     * KEY_DOWN:按下
     * KEY_UP:松开
     */
    cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, function(event){
          
          
        if(event.keyCode == cc.macro.KEY.q){
          
          
            console.debug('你按下了q键!!');
        }
    })
    
  3. custom event

    let that = this;
    //触摸事件
    this.node.on(cc.Node.EventType.MOUSE_DOWN, function(event){
          
          
        //触发自定义事件,第一种
        that.node.emit('myEvent');
        //触发自定义事件,第二种,true控制开启事件冒泡
        that.node.dispatchEvent(new cc.Event.EventCustom("myEvent", true));
    })
    
    //监听自定义事件
    this.node.on('myEvent', function(event){
          
          
        console.debug('自定义事件');
    })
    
  4. Collision detection
    Add collision components, support three types, namely square, circle, polygon, check editing to drag and edit and
    insert image description here
    enable collision detection

    //初始化调用
    start () {
          
          
       //开启碰撞检测
       cc.director.getCollisionManager().enabled = true;
    }
    
    /**
     * 当碰撞产生的时候调用
     * @param  {Collider} other 产生碰撞的另一个碰撞组件
     * @param  {Collider} self  产生碰撞的自身的碰撞组件
     */
    onCollisionEnter(other, self){
          
          
        //获取碰撞组件的tag,来判断碰到的是那个物体
        console.log('碰撞发生' + other.tag);
    }
    
    /**
     * 当碰撞产生后,碰撞结束前的情况下,每次计算碰撞结果后调用
     * @param  {Collider} other 产生碰撞的另一个碰撞组件
     * @param  {Collider} self  产生碰撞的自身的碰撞组件
     */
    onCollisionStay(other, self) {
          
          
        console.log('碰撞持续');
    }
    
    /**
     * 当碰撞结束后调用
     * @param  {Collider} other 产生碰撞的另一个碰撞组件
     * @param  {Collider} self  产生碰撞的自身的碰撞组件
     */
    onCollisionExit(other, self) {
          
          
        console.log('碰撞结束');
    }
    

Guess you like

Origin blog.csdn.net/qq_36303853/article/details/127829550