存档

2012年2月 的存档

Android and IOS game engine

2012年2月29日 没有评论

I’m looking for a 2D game engine to use to target both Android and IOS without the need to rewrite my code. Bonus points if WP7 is supported too.

I found many of them, but they all uses c++. I would really like a game engine that uses an interpreted/high level language(c#, java, python, lua, you say. My preference is toward strong typed ones), productivity with this languages is far better than with C/C++(at least on my side)

I found this ones:

Emo framework

pros:

  • BSD licence
  • Uses interpreted language (Squirrel, ps: never heard of it, but it seams good)

cons:

  • Really simple Api
  • No access to full features of the underlying system (no way to connect with bluetooth or internet using the os api)

Mono

pros:

  • C#
  • WP7 support, + other
  • it seams very well supported

cons:

  • both mono for android and mono for ios are 400$ each. I’m a student and i develop in free time, i have no such money to invest, and if i must chose between the 2, i’ll chose android and stick with AndEngine, that is really good for my needs right now(too sad it is Android only)

Well, i don’t know other engines that work on both platforms and use an interpreted language.

About C++ ones,

cocos2d-x

  • open source
  • C++
  • well documented? (since it is a porting from cocos2d, i expect the tutorials for cocos2d to be useful to cocos2d-x too)
  • WP7 possible porting
  • it doesn’t ease developing for both platform from only pc (obviously a mac is needed in any case to load the app to the store)

Marmalade

Have i missed some good one? I really would like to find a good one that uses an interpreted language, but the one i found is too much expensive or doesn’t fulfil my needs(i need to fully access the networking apis). If such an engine doesn’t exists, i think i’ll use cocos2d-x (since it is open source), but i’m sure i haven’t taken into consideration other engines!

There are many game engines that work for both Android and iOS, 26 by my last count. Take a look at http://mobilegameengines.com/

There is also Unity.

For 2D games you don’t need the Pro version of it, though the non-Pro is still 2*$400 for iOS and Android.

It is well known and uses mono (C#) as the scripting engine.

You also have the option to compile mono for ARM/Android, and use it natively. It is not supported, and you have to create some wrappers around your code, so it can interface with the Android native APIs.

If using commands carefully you can then port this code with some changes to Mono for iOs and XNA (WP7) too

V-Play (v-play.net) is a cross platform 2D game engine based on Qt/QML. API reference.
It already supports iOS, Android, Symbian, MeeGo and Desktop platforms. BlackBerry and Windows Phone support is in progress and will be added soon.
V-Play also comes with ready-to-use game templates for the most successful game genres like tower defense, platform games or puzzle games, several tutorials and demos. (V-Play examples & demos)

(Disclaimer: I’m one of the guys behind V-Play)

I’d also suggest GameSalad, it’s 2D, runs on Android, iOS, and used HTML5 to support Tizen. It’s got a declarative drag-and-drop programming UI (so if you’re looking for traditional text based program it’s not for you). There are many examples and tutorials online and a couple of marketplaces of templates you can use as a starting point. Disclaimer, I’m one of the co-founders.

分类: stackoverflow精选, unity3d 标签:

Color Changing Sprites Cocos2d

2012年2月29日 没有评论

I need my sprite to transition to one color to another and on and on… like blue tint then green then purple, but i cannot find any good actions for that and am wondering, should i use animations? or is there an incorporated action for this?

you can use CCTintTo action to change the color of the sprite

[sprite runAction:[CCTintTo actionWithDuration:2 red:255 green:0 blue:0]];

since i saw several questions about replacing pixel colours in sprites, and i did’nt see any good solution (all solution only tint the color, and none of them is able to change an array of colours without forcing you into creating multiple image layers which construct the final image you want, i.e: one layer for pans, other for show, other for shirt, another for hair colour… and it goes on – note that they do have their advantages like the ability to use accurate gradients)

my solution allows you to change array of colors, meaning you can have a single image with a known colors (you dont want any gradiants in this layer, only colours that you KNOW their values – PS this only applies to colors you intent to change, other pixels can have any colour you want)
if you need gradiants over the colours you change, create an additional image with only the shading and place it as a child of the sprite.

also be aware that i am super-new to cocos2d/x (3 days), and that this code is written for cocos2dx but can be ported to cocos2d easily.

also note that i didnt test it on android only on iOS, i am not sure how capable is android official gcc and how will it deal with the way i allocate _srcC and _dstC, but again, this is easily portable.

so here it goes:

cocos2d::CCSprite * spriteWithReplacedColors( const char * imgfilename, cocos2d::ccColor3B * srcColors, cocos2d::ccColor3B * dstColors, int numColors )
{
    CCSprite *theSprite = NULL;

    CCImage *theImage = new CCImage;
    if( theImage->initWithImageFile( imgfilename ) )
    {
        //make a color array which is easier to work with
        unsigned long _srcC [ numColors ];
        unsigned long _dstC [ numColors ];
        for( int c=0; c<numColors; c++ )
        {
            _srcC[c] = (srcColors[c].r << 0) | (srcColors[c].g << 8) | (srcColors[0].b << 16);
            _dstC[c] = (dstColors[c].r << 0) | (dstColors[c].g << 8) | (dstColors[0].b << 16);
        }

        unsigned char * rawData = theImage->getData();
        int width = theImage->getWidth();
        int height = theImage->getHeight();

        //replace the colors need replacing
        unsigned int * b = (unsigned int *) rawData;
        for( int pixel=0; pixel<width*height; pixel++ )
        {
            register unsigned int p = *b;
            for( int c=0; c<numColors; c++ )
            {
                if( (p&0x00FFFFFF) == _srcC[c] ) 
                {
                    *b = (p&0xFF000000) | _dstC[c];
                    break;
                } 
           }
            b++;
        }

        CCTexture2D *theTexture = new CCTexture2D();
        if( theTexture->initWithData(rawData, kCCTexture2DPixelFormat_RGBA8888, width, height, CCSizeMake(width, height)) )
        {
            theSprite = CCSprite::spriteWithTexture(theTexture);
        }
        theTexture->release();
    }
    theImage->release();

    return theSprite;
}

to use it just do the following:

ccColor3B src[] = { ccc3( 255,255,255 ), ccc3( 0, 0, 255 ) };
ccColor3B dst[] = { ccc3( 77,255,77 ), ccc3( 255, 0 0 ) };
//will change all whites to greens, and all blues to reds. 
CCSprite * pSprite =  spriteWithReplacedColors( "character_template.png", src, dst, sizeof(src)/sizeof(src[0]) );

of course if you need speed, you would create an extension for a sprite that create a pixel shader that does it hw accelerated at render time ;)

btw: this solution might cause some artefacts on the edges on some cases, so you can create a large image and scale it down, letting GL minimise the artefact.
you can also create “fix” layers with black outlines to hide the artefacts and place it on top etc.
also make sure you don’t use these ‘key’ colors on the rest of the image you don’t want the pixels changed.
also keep in mind that the fact that the alpha channel is not changed, and that if you use basic images with pure red/green/blue colors only, you can also optimize this function to eliminate all artefacts on edges automatically (and avoid in many cases, the need for an additional shade layer) and other cool stuff (multiplexing several images into a single bitmap – remember palette animation?)

enjoy ;)

分类: cocos2d, stackoverflow精选 标签:

移动终端网页游戏移植研发框架【人物角色模型介绍】

2012年2月26日 没有评论

    在游戏中游戏人物角色模型的建立是很重要的,人物角色属性包括:角色名,称号,属性【血,攻击,防御】,技能,经验值等,在我们的游戏中,我们还加入了特殊技这样的另类玩法,特殊技其实是一种类型值,玩家可以再战斗中使用特殊技进行战斗的逆转。直接说正题吧,首先分析完之后我们从服务器端的开始,服务器端要有一套标准的人物设置的工具,这样的工具起初建立起来时比较困难,不过后期使用会很多。今天我就将在游戏界面中我们通常看到的类似状态栏一样的工具条做出来,能让玩家直观方便的看到当前自己的状态信息。

   

   服务器端配置工具基本如下图:

   

移动终端网页游戏移植研发框架【人物角色模型介绍】

     其实设置的内容非常多,包括技能,特殊技,道具包,等等一系列关于整个人物属性的操作都需要建立完毕,我这里只截了部分图。让大家了解这个游戏是怎么制作的。首先服务器端配置好之后,客户端就是和服务器端数据请求交互的时候了。

     首先在主界面通常有一查看状态栏的标志:

     

     移动终端网页游戏移植研发框架【人物角色模型介绍】 

     在安卓界面中,UI的设计是多种多样的,这样的界面大家看起来应该不陌生,我们做成了扇形的工具栏,工具栏上面有5个按钮,其中针对每一个按钮设置焦点,距离,及事件!我们在人物的对话框中设置好点击事件,但这是一个交互过程,请求服务器资源后开始进行配置,打开新的窗体展示人物属性。

移动终端网页游戏移植研发框架【人物角色模型介绍】移动终端网页游戏移植研发框架【人物角色模型介绍】View Code

//角色信息
findViewById(R.id.btnPlayerInfo).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

Indicator.endIndicator();
Indicator.beginIndicator(TApp.getActivity(), "查询中", "正在查询,数据加载中...", R.drawable.icon);

thread_getuserinfo = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
pui.setSend_number(usernumber);
pui.Get_GameUserInfos.run();
if (pui.getGetUserInfoList() != null) {
try {
showPlayInfoV();
} catch (Exception e) {
e.printStackTrace();
Indicator.endIndicator();
}
}
}
});
thread_getuserinfo.start();
}


});

    在点击事件中看到有一个请求交互,将玩家的数字账号发送到服务器进行请求后,获取玩家数据。

    之后就是展示:

    移动终端网页游戏移植研发框架【人物角色模型介绍】

    上图就是玩家角色的基本信息,包括了很多属性·····,但是后来我发现,没有经验值,现在补上,而且显示的布局也不够标准。简单修改一下界面吧,然后加上当前经验值和下一级经验值的参数就OK了,详细写一下代码:

移动终端网页游戏移植研发框架【人物角色模型介绍】移动终端网页游戏移植研发框架【人物角色模型介绍】View Code

 <TextView android:id="@+id/tvLevel" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="角色等级" />
<TextView android:id="@+id/tvPlayerName" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="角色姓名" />
<TextView android:id="@+id/tvPlayerChenHao" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="称号" />
<TextView android:id="@+id/tvPlayerJingXue" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="精血"

/>
<TextView android:id="@+id/tvExp" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="当前经验/生升级经验" />
<TextView android:id="@+id/tvPlayerAttack" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="攻击力" />
<TextView android:id="@+id/tvPlayerDefence" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="防御力" />
<TextView android:id="@+id/tvPlayerSkill" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="特殊技" />

    然后是具体里面代码参数赋值:

移动终端网页游戏移植研发框架【人物角色模型介绍】移动终端网页游戏移植研发框架【人物角色模型介绍】View Code

                //人物等级
String playlevel = playerinfo.getUserLevel();
setTextViewText(R.id.tvLevel, "等级:" + playlevel );
//人物经验
String nowexp = playerinfo.getExp();
String nextexp = playerinfo.getNextExp();
setTextViewText(R.id.tvExp, "经验:" + nowexp +"/"+ nextexp);

    修改好,看看效果吧

    移动终端网页游戏移植研发框架【人物角色模型介绍】

    整体小改之后界面就更加详细明了。上面的装备属性,技能属性都是按钮,手指按下去之后继续弹出物品的属性!

   

    移动终端网页游戏移植研发框架【人物角色模型介绍】

    好了,人物属性界面介绍完毕,之后一节,我继续开始制作另一种状态栏,是显示经验值进度条和,血条进度条的。

    有喜欢研究网游的研发爱好者可以加我们的群:45578308。希望你能给我们提出宝贵的意见和建议。之后的章节我会详细说到精灵系统,和战斗系统。相互讨论交流。我现在一直纠结于目前我的战斗系统不够流畅···希望有高手和我一起讨论。

分类: 未分类 标签:

移动终端网页游戏移植研发框架【服务器及客户端交互处理】

2012年2月25日 没有评论

    上回说到:“服务器端的一些简单界面·········”。吃晚饭,继续说一下客户端吧,客户端采用了多层架构,大家对C#的多层架构也比较了解,最标准的就是三层架构了,不一一说了,为了和服务器端的架构匹配,客户端的数据层有简单的重构,就是单独写来对接业务逻辑,没有接口,比较蛋疼的是,当初我和我的朋友商量,是否为了这个游戏单独做一个模块实体生成的工具,但是我们的业务不同就只要放弃这个想法了,不过以后团队大了要实现这个东西。实现这个数据层的接口工具的好处就是,服务器端有一些业务和底层需要修改的时候,执行这个工具后客户端对应也会生成或修改这样的模块的数据接口。我们大概花了半个月的时间来处理对接服务器端和客户端的底层数据。

   先来看一下服务器端有什么标准吧,从数据库入手:

   1,数据库对应的服务器端的模型需要独立出来,为以后的区划分做准备,一台服务器上,可以划分出3个区来供玩家进行游戏,每个区容量具体暂时此处不详细说。

   2,服务器端对应的客户端的访问接口也需要独立,但是模型是统一的,比如一个角色根据一个数字ID进行数据标识。

   

移动终端网页游戏移植研发框架【服务器及客户端交互处理】

       这个是最标准的多层架构了,在里面加入了一些工具,但最主要的还是和客户端通信用的接口了。 这就是我们的服务器端;

      

移动终端网页游戏移植研发框架【服务器及客户端交互处理】

    客户端的结构,也很一目了然,里面的元素也很多,主体思想就是客户端的架构和服务器端的相差不多。具体还得看里面的内容嘛,客户端有两个比较重要的部分,一个是serverapi,一个是remote。分别都是处理服务器交互和逻辑的。从服务器端得到的数据都要通过他们,再到业务逻辑处理,最后到视图。

    详细说一下我们的游戏的未来的运营规划吧,移动市场和PC市场还不一样,智能手机的数量2010年来至今是突飞猛进的增长,2011年的时候有位同仁统计过苹果和安卓数量的文章,说到2012年估计就没人统计了,因为,这个已经没有意义了,移动市场将会瓜分PC机市场。无论是广告业,电子商务,移动市场再将来都会成为主流,如今,手机上有WIFI,和2G,3G一说,其实很多应用,游戏业针对这些做过处理方案,打个比方,三国杀,用2G,3G来玩很多用户还是表示非常有压力的!这个问题我想说的是,用户是上帝,我们要尊重上帝,我觉得我们这款游戏这些用户都会考虑,而且我要重点考虑让2G,3G用户跑起来都毫无压力。我们就挖掘游戏底层里面的等待机制,做成一种工具,就是不要让服务器去主动获取客户端的请求,而是让玩家处于半离线状态游戏,我看是在玩游戏,但其实是单机状态,等我进行某一些交互操作【PK/战斗/聊天】的时候才进行主动交互。所以我们服务器有2种通行模式,即时和非即时,这就是PC机客户端,网页游戏==和手机网游的区别。三国杀也类似移植,其实2台服务器都是即时通行的,网速不给力,就完不成咯·····

   下面用图来表示一下:

   

移动终端网页游戏移植研发框架【服务器及客户端交互处理】

   OK,有了如此的交互,2G/3G用户相信跑起来也没有压力,我进入游戏的时候判断一下,我手机当前状态就行,进入我对应的游戏区服,体验高品质的游戏。

   好了,下回就真的要展示一下游戏界面了,让大家感受一下手机网游不一样的体验和感觉。我们的游戏体验群【45578308】

分类: 未分类 标签:

移动终端网页游戏移植研发框架【android&IOS总汇】

2012年2月25日 没有评论

     很久没来博客园逛了,其实是一直抽不出时间啊,我也希望在这里记录下我工作的点点滴,平日工作较忙,基本上没时间做什么其他时间的,都说时间就像海绵,是挤出来的。有点道理,所以我今年2012年回归博客园,并且将我今年的项目和计划和大家分享,只是经验分享罢了,其中商业性的东西我就不一一详解,毕竟整个移动终端市场是非常不稳定的,还记得我去年我在博客园写下了几篇安卓应用总汇的文章,当时是举了一个例子,写了一个安卓理财软件的制作思路,其实只是个安卓入门的思路罢了,古人说的好:师傅领进门,修行在个人,其实我们学习的并不是移动终端的技术,玩的更是这块市场,有人说了,这是块肥肉,我不否认。相信了解市场的业内朋友对这块肥肉已经啃到嘴里面去了,但是这块市场想求稳定,是也是非常困难的。每个人角度不同,想问题的思路也会不同,项目规划也就不同。我在我自己的公司,我带领的团队目前已经有3款以上成功应用在移动终端市场上线,效果非常不错,听听堂就是我们的一款精品项目www.tingtingtang.com。目前也在计划改版中,相信不久的将来这款应用将推广到各位的手机上。而我个人的应用多大数十款应用也已经上线。

    下面也就详细和大家分享一下我2012年的一些项目吧,由于我前几年一直都在游戏公司工作,并且做的是网页游戏。我对网页游戏的研发框架也有一定的了解,综合对手机移动终端的市场,我今年的项目也就是这个“游戏”。是一款在线页游的移动终端版本。这款页游题材是一款武侠类型的大型网页游戏【回合制】。项目的立项是在2011年11月份,目前项目已经完成了50%左右进度,如果大家了解,玩过网页游戏的可以知道现在的网页游戏,已经将2DRPG客户端移植到网页了。大部分的网页游戏都已经成熟化,并且泛滥。但是真正属于一款移动终端的网络游戏,是少之又少的,三国杀,QQ游戏这些比较成功,少数其他的都是通过客户端移植内嵌WEBview的形式展示,且不说移植的可靠性,和可玩性大大降低不说,单独界面就很让人讨厌和提的起兴趣,三国杀和QQ游戏的UI是非常成功的。所以,单独为移动终端研发的产品,才是我,我们要做的真正的事情,而并非移植!下面我单独将我的项目资料贴一点图给大家鉴赏吧,游戏项目叫做 “剑神客栈”,目前安卓版本项目进度已经完成了50%, IOS项目进度已经开始建模。至于具体的框架和模型稍后会和大家慢慢分享。这也是一个美妙的旅程,下面每周我的会抽时间来和大家分享我们的游戏,我们建了一个QQ群【45578308】,和大家一起讨论游戏研发,和游戏测试的群。如果对剑神客栈有兴趣的朋友可以加入进来和我们一起体验游戏。

    

移动终端网页游戏移植研发框架【android&amp;IOS总汇】

     重装了一下系统今天,就顺带从新在svn上down一下最新的项目。后面的是我们服务器端,可以看到一些大致的后台功能设置,这套架构服务器端使用的是C#,有一些工具是用VS做的,部分工具,例如服务器区服管理器用WPF来写,具体后台就写成WEB版本的,简单快捷,做游戏就是做工具,一些列的工具零部件才能给一款好的游戏作品做好铺垫和运营的准备。

    下面我截一些完整的后台服务配置的功能图,大家就知道我们这款游戏的大致框架了:

     

移动终端网页游戏移植研发框架【android&amp;IOS总汇】

移动终端网页游戏移植研发框架【android&amp;IOS总汇】

移动终端网页游戏移植研发框架【android&amp;IOS总汇】

移动终端网页游戏移植研发框架【android&amp;IOS总汇】

 

大致上就是这几块,而其中还少了一些其他的配置,写在另外的一套里面的,包含了任务系统,和客户端控制和管理的系统。

之后我会写一些服务器端和客户端配置的一些基本要点和元素。

分类: 未分类 标签:

How do I make water as seen in Sea Stars?

2012年2月14日 没有评论

There is a nice Sea Stars iOS application out there, with a good looking water effect can be seen on video.

I have found Tiny Wings “waves” tutorial on here, so I guess I can figure out how to make waves.

I wonder how do I make effect when hero pops out of the water (splash and water deformation). Also I wonder how do I make effect when I look on water line from above and from below – please notice how water line changes when hero is above it and below it.

I am familiar with Box2d and Cocos2d, so I wonder if this can be done within that knowledge. Also I wonder if Chipmunk can help.

It looks like the waves in sea stars aren’t really simulated, but just simple perlin noise and adding a simple bump when making a splash. If you want water simulation, I posted some code I wrote to do that here:
http://www.cocos2d-iphone.org/forum/topic/25494

分类: stackoverflow精选, unity3d 标签:

Cocos2D project with many scenes does not release memory properly

2012年2月11日 没有评论

I’ve got a great problem and I don’t understand very well why occurs. This is the case:

  • Have a great project in Cocos2D with 10 scenes. Each scenes is a page of a book with huge sprites. It uses Kobold2D 1.0.2 implementation.
  • Every page has common objects in a singleton class, to put a common menus via LayerColor.
  • The sprites is TexturePacker in PVR.CCZ RGBA4444 and in iPad memory
    are around 16-20Mb every spritesheet loaded.
  • I use CCTransitionTurnPage for replaceScene for one to the next one.
  • At init method of each page (class), load the texture and FrameFile.
  • At onExit method of each page (class), unload the textures and frameFile. I used the dumpCachedTextureInfo and says me textures load and unload from memory perfectly.
  • Of course, I remove from child all objects. All my sprites are common variables declared on the interface section at .h, because I need to access them in every method of the class.
  • My project is made with Kobold2D integration in a ARC project (but you know the attached Kobold2D project has ARC not enabled for compatibility problem)

The fact is when I start the project, everything seems perfect but memory is increasing for every scenes (page) I made. Page1: 30Mb., Page2: 40, Page 3: 54, Page 4: 65… After 7 or 8 scenes, Instruments, Xcode or the iPad itself hangs the application without any message (except Instruments with a final Low memory Warning).

Why there’s no memory releasing after each scenes? Maybe it’s because ARC and the no super dealloc variable. Why textures appears unload perfectly but seems like there’s no unload because memory is growing without control until crash?

I was having a similar problem with memory retention and no leaks showing up in instruments. I couldn’t get -(void) dealloc to even get called until I wrote the following into every scene’s .m file:

-(void) onExit {
    //unschedule selectors to get dealloc to fire off
    [self unscheduleAllSelectors];
    //remove all textures to free up additional memory. Textures get retained even if the sprite gets released and it doesn't show as a leak. This was my big memory saver
    [[CCTextureCache sharedTextureCache] removeAllTextures];
    [super onExit];
}

After implementing this, my memory was released after every replaceScene: was called. Hope this is of some use to you.

After months of working, I learned the most important lesson on Cocos2D. The retain increase by one when you put any CCNode object on a CCArray or NSArray or NSDictionary… This means you must release the objects from this objects before the CCLayer or CCScene dealloc.

You must put a [array removeAllObjects] or [dictionary release] on the -(void)cleanup and after all your objects has removed, then put a [super cleanup];

In the meantime, on -(void)onExit you must remove all scheduler from the instance. Not only a scheduler itself. Remember to stopAllActions on any CCNode. But, carefully, because stoping actions from CCNodes (Sprites or something) must be on cleanup, before any removeAllObjects.

And remember: if CCLayer or CCScene does not remove properly, SimpleAudioEngine not will release the audio too.

Thanks in advance to all of you

分类: cocos2d, stackoverflow精选 标签:

How to rotate coordinate system?

2012年2月8日 没有评论

I am trying to find the new value of a coordinate if I rotate around the origin.

For example, say I have the point (1,1).
If I rotate the coordinate axis 45 degrees around the origin, the transformed coordinate would be (0,1.414)

Is there a way to do this efficiently in cocos2d, or in objective-c ?
Even answers explaining the math to do this would be helpful.

See this page:
http://www.siggraph.org/education/materials/HyperGraph/modeling/mod_tran/2drota.htm

This is the formula:

x’ = x cos f – y sin f

y’ = y cos f + x sin f

Remember that sin and cos takes radians, so you have to do like this:

double x,y;
double newX,newY;
double angle;

//Test values:
x=1;
y=1;
angle = 45;

double rad = angle*M_PI/180;

newX = x * cos(rad) - y * sin(rad);
newY = y * cos(rad) + x * sin(rad);

I didn’t test this, so there might be typos… ;)

分类: stackoverflow精选, unity3d 标签:

playing video on top of OpenGL view in android

2012年2月6日 没有评论

I’m developing a game using cocos2d-x and I want to play video in it.
The activity has one OpenGL view and I also put additional VideoView on top of it and set visibility to INVISIBLE.

When I need to play video, I just hide OpenGL view and enable my VideoView. After that I create MediaPlayer, call setDisplay with holder of that VideoView, etc. and eventually video plays well. When video finishes, I switch visibilities back again – opengl to VISIBLE and videoview to INVISIBLE.

However, the problem is that when I try to play video second time, it just doesn’t show up, however, sound from the video is being played.

Is there any catch with visibilities?

I just modified the ApiDemo to see whether it works. I have blog the full code here : post without using separate media player for video view we can set the video and play

   mVideoView.setVideoURI(data.getData());
   mVideoView.setVisibility(View.VISIBLE);
   mVideoView.start();

   //I could add touch listener in onCreate
    mGLSurfaceView.setOnTouchListener(...);

//touch event will go all the way down to GLSurfaceView
//Here i could chnage the video view position
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    mVideoView.setTranslationX(motionEvent.getX());
    mVideoView.setTranslationY(motionEvent.getY());
    return true;
}

You will need a surfaceview to play video at using android MediaPlayer class.

To play video above GLSurfaceView, create an android Custom Dialog which contains a surfaceView and play video on that.

You can do this by adding dynamically video view on the surface of glview. First create a parent view (any layout) add video view in same parent view then add this parent view on the gl surface view. I have done this before and it was working for me. for your reference :

     // first set the content view as your glview with your params.
     setContentView(mGLView, gl_params);
     mGLView.setZOrderMediaOverlay(false);

     // add a parent view for video view. rl is relative layout
     addContentView(rl, rl_params);

     // now add the video view inside this parent view.
     rl.addview(video_view, video_view_params)
分类: stackoverflow精选, unity3d 标签:

Cocos2d – Initial app layer displays incorrectly on app load, displays appropriately after reload

2012年2月3日 没有评论

I’m using a GameManager singleton to handle some of the shared tasks required by my game. One of those tasks is loading individual game scenes. When the game starts up, whichever scene/layer combo I have displayed appears incorrectly; it looks like maybe the coordinates that items are positioned in relation to are wrong.

It doesn’t matter which layer I choose–they all appear incorrectly. If you click on a button and load another scene/layer, then go back to the scene/layer in question, everything displays correctly. This only happens on retina display devices, so I think it might be related to the scaling I set for the different display types in the game manager. However, changing the scaling for Retina displays breaks things even more (the layers are too small).

Here’s my AppDelegate.h

#import <UIKit/UIKit.h>

@class RootViewController;

@interface AppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow            *window;
    RootViewController  *viewController;
}

@property (nonatomic, retain) UIWindow *window;

@end

AppDelegat.m

#import "cocos2d.h"

#import "AppDelegate.h"
#import "GameConfig.h"
#import "RootViewController.h"
#import "GameplayScene.h"
#import "GameManager.h"

@implementation AppDelegate

@synthesize window;

- (void) removeStartupFlicker
{
#if GAME_AUTOROTATION == kGameAutorotationUIViewController
#endif
}


- (void) applicationDidFinishLaunching:(UIApplication*)application
{
    // Init the window
    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Try to use CADisplayLink director
    // if it fails (SDK < 3.1) use the default director
    if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
        [CCDirector setDirectorType:kCCDirectorTypeDefault];


    CCDirector *director = [CCDirector sharedDirector];

    // Init the View Controller
    viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
    viewController.wantsFullScreenLayout = YES;

    EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
                                   pixelFormat:kEAGLColorFormatRGB565   // kEAGLColorFormatRGBA8
                                   depthFormat:0                        // GL_DEPTH_COMPONENT16_OES
                        ];

    // attach the openglView to the director
    [director setOpenGLView:glView];
    [director setDeviceOrientation:kCCDeviceOrientationPortrait];

    [director setAnimationInterval:1.0/60];
    [director setDisplayFPS:YES];


    // make the OpenGLView a child of the view controller
    [viewController setView:glView];

    // make the View Controller a child of the main window
    [window addSubview: viewController.view];

    [window makeKeyAndVisible];

    [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];


    // Removes the startup flicker
    [self removeStartupFlicker];

    // Run the intro Scene
    //[[CCDirector sharedDirector] runWithScene:[GameplayScene node]];
    [[GameManager sharedGameManager] runSceneWithID:kMainMenuScene];
}

- (void)dealloc {
    [[CCDirector sharedDirector] end];
    [window release];
    [super dealloc];
}

GameManager.h

#import <Foundation/Foundation.h>
#import "Constants.h"
#import "CommonProtocols.h"

@interface GameManager : NSObject {
    BOOL isMusicON;
    BOOL isSoundEffectsON;
    BOOL hasPlayerDied;
    BOOL newHighScore;
    BOOL newBestTime;
    BOOL isUiTextLeft;
    int currentScore;
    int highScore;
    int lengthPlayed;
    int bestTime;
    int randomPurple;
    int randomGreen;
    int timeBonus;
    int timeTillDeath;
    int uiBackgroundHeight;
    CharacterStates previousPurpleState;
    CharacterStates previousGreenState;
    SceneTypes currentScene;
}

@property (readwrite) BOOL isMusicON;
@property (readwrite) BOOL isSoundEffectsON;
@property (readwrite) BOOL hasPlayerDied;
@property (readwrite) BOOL newHighScore;
@property (readwrite) BOOL newBestTime;
@property (readwrite) BOOL isUiTextLeft;
@property (readwrite) int currentScore;
@property (readwrite) int highScore;
@property (readwrite) int lengthPlayed;
@property (readwrite) int bestTime;
@property (readwrite) int randomPurple;
@property (readwrite) int randomGreen;
@property (readwrite) int uiBackgroundHeight;
@property (readwrite) CharacterStates previousPurpleState;
@property (readwrite) CharacterStates previousGreenState;
@property (readwrite) int timeBonus;
@property (readwrite) int timeTillDeath;

+(GameManager*)sharedGameManager;
-(void)runSceneWithID:(SceneTypes)sceneID;
-(void)openSiteWithLinkType:(LinkTypes)linkTypeToOpen ;

@end

GameManager.m

#import "GameManager.h"
#import "GameplayScene.h"
#import "MainMenuScene.h"
#import "OptionsScene.h"
#import "CreditsScene.h"
#import "IntroScene.h"
#import "LevelCompleteScene.h"

@implementation GameManager

static GameManager* _sharedGameManager = nil; 
@synthesize isMusicON;
@synthesize isSoundEffectsON;
@synthesize hasPlayerDied;
@synthesize newHighScore;
@synthesize newBestTime;
@synthesize isUiTextLeft;
@synthesize currentScore;
@synthesize highScore;
@synthesize lengthPlayed;
@synthesize bestTime;
@synthesize previousPurpleState;
@synthesize previousGreenState;
@synthesize randomPurple;
@synthesize randomGreen;
@synthesize timeBonus;
@synthesize timeTillDeath;
@synthesize uiBackgroundHeight;

+(GameManager*)sharedGameManager {
    @synchronized([GameManager class])
    {
        if(!_sharedGameManager)
            [[self alloc] init]; 
        return _sharedGameManager;
    }
    return nil; 
}

+(id)alloc {
    @synchronized([GameManager class]){
        NSAssert(_sharedGameManager == nil, @"Attempted to allocate a second instance of the Game Manager singleton");
        _sharedGameManager = [super alloc];
        return _sharedGameManager;
    }
    return nil;
}

-(id) init {
    self = [super init];
    if (self != nil) {
        // Game manager initialized
        CCLOG(@"Game manager singleton, init");
        hasPlayerDied = NO;
        // DECODING INFO FROM DEFAULTS
        NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [dirPaths objectAtIndex:0];

        NSMutableData *gameData;
        NSKeyedUnarchiver *decoder;

        NSString *documentPath = [documentsDirectory stringByAppendingPathComponent:@"gameState.dat"];
        gameData = [NSData dataWithContentsOfFile:documentPath];

        if (gameData) {
            decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:gameData];

            highScore = [decoder decodeIntForKey:@"highScore"];
            bestTime = [decoder decodeIntForKey:@"bestTime"];
            isMusicON = [decoder decodeBoolForKey:@"isMusicON"];
            isSoundEffectsON = [decoder decodeBoolForKey:@"isSoundEffectsON"];
            isUiTextLeft = [decoder decodeBoolForKey:@"isUiTextLeft"];
            //currentScore = [decoder decodeIntForKey:@"currentScore"];

            [decoder release];
        } else {
            highScore = 0;
            bestTime = 0;
            isMusicON = TRUE;
            isSoundEffectsON = TRUE;
            isUiTextLeft = TRUE;
            //currentScore = 0;
        }

        CCLOG(@"Music - %s", isMusicON ? "true" : "false");
        CCLOG(@"Sound - %s", isSoundEffectsON ? "true" : "false");
        //****************************
        currentScore = 0;
        timeBonus = 0;
        timeTillDeath = 0;
        uiBackgroundHeight = 0;
        currentScene = kNoSceneUninitialized;
    }

    return self;
}

-(void)runSceneWithID:(SceneTypes)sceneID {

    SceneTypes oldScene = currentScene;
    currentScene = sceneID;
    id sceneToRun = nil;

    switch (sceneID) {
        case kMainMenuScene:
            sceneToRun = [MainMenuScene node];
            break;
        case kOptionsScene:
            sceneToRun = [OptionsScene node];
            break;
        case kCreditsScene:
            sceneToRun = [CreditsScene node];
            break;
        case kIntroScene:
            sceneToRun = [IntroScene node];
            break;
        case kLevelCompleteScene:
            sceneToRun = [LevelCompleteScene node];
            break;
        case kGameplayScene:
            sceneToRun = [GameplayScene node];
            break;
        default:
            CCLOG(@"Unknown ID, cannot switch scenes");
            return;
            break;
    }

    if (sceneToRun == nil) {
        // Revert back, since no new scene was found
        currentScene = oldScene;
        return;
    }

    // Menu Scenes have a value of < 100
    if (sceneID < 100) {

        if ([[CCDirector sharedDirector] enableRetinaDisplay:YES]) {
            // iPhone 4 Retina
            [sceneToRun setScaleX:1.0f];
            [sceneToRun setScaleY:1.0f];
            CCLOG(@"GM:Scaling for iPhone 4 (retina)");
        } else {
            [sceneToRun setScaleX:1.0f];
            [sceneToRun setScaleY:1.0f];
            CCLOG(@"GM:Scaling for iPhone 3G(non-retina)");
        }
    }

    if ([[CCDirector sharedDirector] runningScene] == nil) {
        [[CCDirector sharedDirector] runWithScene:sceneToRun];
    } else {
        [[CCDirector sharedDirector] replaceScene:sceneToRun];
    }
}

You are calling node with the scene objects call [MainMenuScene scene];and try

and make this method with return type CCScene* and use to get return the scene and write

[[CCDirector sharedDirector]runWithScene:[obj runSceneWithID:1]];

Edit –

-(CCScene*)runSceneWithID:(SceneTypes)sceneID {

    SceneTypes oldScene = currentScene;
    currentScene = sceneID;
    id sceneToRun = nil;

    switch (sceneID) {
        case kMainMenuScene:
            sceneToRun = [MainMenuScene node];
            break;
        case kOptionsScene:
            sceneToRun = [OptionsScene node];
            break;
        case kCreditsScene:
            sceneToRun = [CreditsScene node];
            break;
        case kIntroScene:
            sceneToRun = [IntroScene node];
            break;
        case kLevelCompleteScene:
            sceneToRun = [LevelCompleteScene node];
            break;
        case kGameplayScene:
            sceneToRun = [GameplayScene node];
            break;
        default:
            CCLOG(@"Unknown ID, cannot switch scenes");
            return nil;
            break;
    }

    if (sceneToRun == nil) {
        // Revert back, since no new scene was found
        currentScene = oldScene;

    }
    return sceneToRun;
}

I ran into a similar problem once, but I can’t seem to relate it directly to your code.

In short, the issue is that while I am building my layer/scene in the init method, the nodeToWorldTransformation (at least, possibly others as well) is not set. So, if you are trying to calculate the world coordinates (or possibly the size in world coordinates) of something, it does not work.

Now, in may case, I used that transform to calculate a scale factor at init time, and it was wrong. If I delayed the calculation to after the transformation was set, then everything was ok. The transformation becomes ready only after the layer you are creating has been added to its parent, but I am not exactly sure when it does. Finally, in my case I simply hardcoded the transformation, knowing all dimensions at init time.

It seems that your case could be analogous to this, but, as I said, I cannot relate this to your code.

分类: cocos2d, stackoverflow精选 标签: