当前位置: 首页 > 工具软件 > Cocos2d-html5 > 使用案例 >

初学cocos2d html5

壤驷鸿祯
2023-12-01

初学 cocos2d-html5

<canvas id="gameCanvas" width="320" height="480"></canvas> 设置窗口大小

<link rel="icon" type="image/GIF" href="res/favicon.ico"/> 设置ico

<meta name="viewport" content="user-scalable=no"/>

<canvas id="gameCanvas" width="320" height="480"></canvas>初始化游戏界面大小(后面可变)


适配

    cc.view.adjustViewPort(true);

    cc.view.setDesignResolutionSize(320,480,cc.ResolutionPolicy.SHOW_ALL);

    cc.view.resizeWithBrowserSize(true);

    cc.director.setProjection(cc.Director.PROJECTION_2D);


模板文件夹中要添加 frameworks 才能正常运行


cc.LoaderScene.preload(g_resources, function () {

        cc.director.runScene(new HelloWorldScene());

    }, this); 会显示加载进度


ctor:function () { 构造函数


打开project.json,在jsList字段加入StartScene.js的路径。


cc.Scene.extendCocos2d-JS提供的Scene继承方法



创建场景

var HelloWorldScene = cc.Scene.extend({

    onEnter:function () {

        this._super();

        var layer = new HelloWorldLayer();

        this.addChild(layer);

    }

});

cc.director.runScene(new cc.TransitionFade(1.2, scene));


创建层

var HelloWorldLayer = cc.Layer.extend({

    sprite:null,

    ctor:function () {



创建标签

var _label = new cc.LabelTTF("hellow world", "", 38);


创建精灵 设置属性

this.sprite = new cc.Sprite(res.HelloWorld_png);

        this.sprite.attr({

            x: size.width / 2,

            y: size.height / 2,

            scale: 0.5,

            rotation: 180

        });


执行动作

this.sprite.runAction(

            cc.sequence(

                cc.rotateTo(2, 0),

                cc.scaleTo(2, 1, 1)

            )

        );


helloLabel.runAction(

            cc.spawn(

                cc.moveBy(2.5, cc.p(0, size.height - 40)),

                cc.tintTo(2.5,255,125,0)

            )

        );


播放声音

cc.audioEngine.setMusicVolume(0.7);

cc.audioEngine.playMusic(res.mainMainMusic_mp3, true);

cc.audioEngine.stopMusic();

cc.audioEngine.stopAllEffects();


创建菜单按钮

var newGame = new cc.MenuItemSprite(newGameNormal, newGameSelected, newGameDisabled, function () {

            this.onButtonEffect();

            //this.onNewGame();

            flareEffect(flare, this, this.onNewGame);

        }.bind(this));

        var gameSettings = new cc.MenuItemSprite(gameSettingsNormal, gameSettingsSelected, gameSettingsDisabled, this.onSettings, this);

        var about = new cc.MenuItemSprite(aboutNormal, aboutSelected, aboutDisabled, this.onAbout, this);


        var menu = new cc.Menu(newGame, gameSettings, about);

        menu.alignItemsVerticallyWithPadding(10);

        this.addChild(menu, 1, 2);


——————————————

 var item1 = new cc.MenuItemToggle(

            new cc.MenuItemFont("On"),

            new cc.MenuItemFont("Off") );

        item1.setCallback(this.onSoundControl );

        var state = MW.SOUND ? 0 : 1;

        item1.setSelectedIndex(state);



创建定时器

this.schedule(this.update, 0.1);

update:function () {}


随机数

Math.random() * winSize.width;


创建点坐标

cc.p(x,y);


使用纹理缓存


cc.spriteFrameCache.addSpriteFrames(res.textureTransparentPack_plist);

var cacheImage = cc.textureCache.addImage(res.menuTitle_png);

var title = new cc.Sprite(cacheImage, cc.rect(0, 0, 134, 34));


用户事件

  // accept touch now!

       if (cc.sys.capabilities.hasOwnProperty('keyboard'))

            cc.eventManager.addListener({

                event: cc.EventListener.KEYBOARD,

                onKeyPressed:function (key, event) {

                    MW.KEYS[key] = true;

                },

                onKeyReleased:function (key, event) {

                    MW.KEYS[key] = false;

                }

            }, this);


        if ('mouse' in cc.sys.capabilities)

            cc.eventManager.addListener({

                event: cc.EventListener.MOUSE,

                onMouseMove: function(event){

                    if(event.getButton() == cc.EventMouse.BUTTON_LEFT)

                        event.getCurrentTarget().processEvent(event);

                }

            }, this);


        if (cc.sys.capabilities.hasOwnProperty('touches')){

            cc.eventManager.addListener({

                prevTouchId: -1,

                event: cc.EventListener.TOUCH_ALL_AT_ONCE,

                onTouchesMoved:function (touches, event) {

                    var touch = touches[0];

                    if (this.prevTouchId != touch.getId())

                        this.prevTouchId = touch.getId();

                    else event.getCurrentTarget().processEvent(touches[0]);

                }

            }, this);

        }


 if( 'touches' in cc.sys.capabilities )

            cc.eventManager.addListener(cc.EventListener.create({

                event: cc.EventListener.TOUCH_ALL_AT_ONCE,

                onTouchesEnded:function (touches, event) {

                    if (touches.length <= 0)

                        return;

                    event.getCurrentTarget().moveSprite(touches[0].getLocation());

                }

            }), this);

        else if ('mouse' in cc.sys.capabilities )

            cc.eventManager.addListener({

                event: cc.EventListener.MOUSE,

                onMouseUp: function (event) {

                    event.getCurrentTarget().moveSprite(event.getLocation());

                }

            }, this);


精灵触摸

ctor: function(){

        this._super();

        cc.eventManager.addListener({

            event: cc.EventListener.TOUCH_ONE_BY_ONE,

            swallowTouches: true,

            onTouchBegan: this.onTouchBegan,

            onTouchMoved: this.onTouchMoved,

            onTouchEnded: this.onTouchEnded

        }, this);

    },


onTouchBegan:function (touch, event) {

        var target = event.getCurrentTarget();

        if (target._state != PADDLE_STATE_UNGRABBED) return false;

        if (!target.containsTouchLocation(touch)) return false;


        target._state = PADDLE_STATE_GRABBED;

        return true;

    },

    onTouchMoved:function (touch, event) {

        var target = event.getCurrentTarget();

        // If it weren't for the TouchDispatcher, you would need to keep a reference

        // to the touch from touchBegan and check that the current touch is the same

        // as that one.

        // Actually, it would be even more complicated since in the Cocos dispatcher

        // you get Array instead of 1 cc.Touch, so you'd need to loop through the set

        // in each touchXXX method.

        cc.assert(target._state == PADDLE_STATE_GRABBED, "Paddle - Unexpected state!");


        var touchPoint = touch.getLocation();

        //touchPoint = cc.director.convertToGL( touchPoint );


        target.x = touchPoint.x;

    },

    onTouchEnded:function (touch, event) {

        var target = event.getCurrentTarget();

        cc.assert(target._state == PADDLE_STATE_GRABBED, "Paddle - Unexpected state!");

        target._state = PADDLE_STATE_UNGRABBED;

    },


拆分字符串

var   str="123,4567,89,0";
var a=str.split(",");
alert(a.length);//4数组长度为4
alert(a[0]);
return true;


字符串转json

  1. function ConvertToJsonForJs() {  
  2.           //var testJson = "{ name: '小强', age: 16 }";(支持)  
  3.           //var testJson = "{ 'name': '小强', 'age': 16 }";(支持)  
  4.           var testJson = '{ "name": "小强", "age": 16 }';  
  5.           //testJson=eval(testJson);//错误的转换方式  
  6.           testJson = eval("(" + testJson + ")");  
  7.           alert(testJson.name);  
  8.       }  

 类似资料: