Saturday, October 31, 2015

How Disable Cocos2d-x Texture anti-aliasing especially for pixel art game

When working with games which are using pixel art , usually the game needs to keep the look of the pixel images sharp / none blurred .. now when we working with pixel art the images are small and they are scaled to be bigger , and while they become bigger OpenGL Smears the look on the image .
it can be fixed with small OpenGL command .

1. Here is example of small pixel art animation i made BEFORE the fix see how it looks:
i have 2 framed animation converted to *.plist and then to sprite frames in the code .

The 2 frame animation png file :
The Compiled Scene:



Not much to say it looks like Sh**t. see how blurry it is .
To fix it

2. The source code which contains the Fix  Lines: 5-6:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
 auto cache = SpriteFrameCache::getInstance();
    cache->addSpriteFramesWithFile("sprites.plist", "sprites.png");
    auto sprite = Sprite::createWithSpriteFrameName("sprite_1.png");
    //Disable Texture anti-aliasing 
    Texture2D::TexParams texParams = { GL_NEAREST, GL_NEAREST, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE };
    sprite->getTexture()->setTexParameters(texParams);
    sprite->setScale(6.0f);
    auto spriteBatch = SpriteBatchNode::create("sprites.png");
    spriteBatch->addChild(sprite);
    this->addChild(spriteBatch);    
    sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
    Vector<SpriteFrame*> animFrames(2);
    char str[100] = { 0 };
    for (int i = 1; i <= 2; i++)
    {
        sprintf(str, "sprite_%d.png", i);
        auto frame = cache->getSpriteFrameByName(str);
        animFrames.pushBack(frame);
    }
    auto animation = Animation::createWithSpriteFrames(animFrames, 0.3f);
    // 14 frames * 1sec = 14 seconds
    sprite->runAction(RepeatForever::create(Animate::create(animation)));


As we can see the function setTexParameters let us set custom parameters to our Sprite Texture which contains the animation frames  and the way it should render 
This is how it looks like after the FIX :


Much much better .

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.