I am trying to rotate my sprite when i push to go left. right now my character is idling and running to the right. but im having trouble rotating to the left.
here is my chunk of code. if anyone could help me, that would be awesome.
public void draw(SpriteBatch spriteBatch) {
stateTime += Gdx.graphics.getDeltaTime();
//continue to keep looping
if(Gdx.input.isTouched()){
int xTouch = Gdx.input.getX();
int yTouch = Gdx.input.getY();
//System.out.println(Gdx.graphics.getWidth()/4);
//go left
if(xTouch < (width/4) && yTouch > height - (height/6)){
currentRunFrame = runAnimation.getKeyFrame(stateTime, true);
spriteBatch.draw(currentRunFrame, runSprite.getX() - 32, runSprite.getY() + 150, 128, 128);
RealGame.leftButton = new Texture(Gdx.files.internal("leftButtonOver.png"));
moveLeft();
}
if(xTouch > (width/4) && xTouch < (width/4)*2 && yTouch > height - (height/6)){
currentRunFrame = runAnimation.getKeyFrame(stateTime, true);
spriteBatch.draw(currentRunFrame, runSprite.getX() - 32, runSprite.getY() + 150, 128, 128);
RealGame.rightButton = new Texture(Gdx.files.internal("rightButtonOver.png"));
moveRight();
}
if(xTouch > (width/4) * 2 && xTouch < (width/4) * 3 && yTouch > height - (height/6)){
RealGame.shootButton = new Texture(Gdx.files.internal("shootButtonOver.png"));
}
if(xTouch > (width/4) * 3 && xTouch < (width/4) * 4 && yTouch > height - (height/6)){
RealGame.jumpButton = new Texture(Gdx.files.internal("jumpButtonOver.png"));
}
}
if(!Gdx.input.isTouched()){
currentIdleFrame = idleAnimation.getKeyFrame(stateTime, true);
spriteBatch.draw(currentIdleFrame, idleSprite.getX() - 32, idleSprite.getY() + 150, 128, 128);
RealGame.leftButton = new Texture(Gdx.files.internal("leftButton.png"));
RealGame.rightButton = new Texture(Gdx.files.internal("rightButton.png"));
RealGame.shootButton = new Texture(Gdx.files.internal("shootButton.png"));
RealGame.jumpButton = new Texture(Gdx.files.internal("jumpButton.png"));
moveStop();
}
}
thank you in advance, and let me know if you need more info.
I assume your currentIdleFrame is a Texture or TextureRegion, not a Sprite. One of SpriteBatchs draw methode with Texture supports a flipX and flipY. Using this you can flip him, for example if you are walking to the left, but your Texture is facing to the right. Also this supports rotation, which should be the rotation in degrees.
Verry important note: You create new Texture every render loop. Don't do this. Instead load all your Textures in a Texture[] frames and draw the right one, depending on stateTime. Also take a look at Animations class, which will help you with this.
Hope i could help
Use a SpriteBatch draw method that takes boolean flipX parameter or call flip on the Sprite.
Oh, and if this is your main loop, stop loading the textures like you are. Load them in the beginning and just swap them as needed.
Related
I use RenderTexture to render a layer with all its nodes to a texture then apply an OpenGL shader on that texture to create post-process effects. It works all fine except with Sprite3D and Billboard nodes. It has been asked on their forums a few times without any response. I wonder if anyone got this to work.
Here is an example:
Layer* gameLayer = Layer::create();
this->addChild(gameLayer, 0);
auto dir = Director::getInstance()->getWinSize();
Camera *camera = Camera::createPerspective(60, (GLfloat)dir.width / dir.height, 1, 1000);
camera->setPosition3D(Vec3(0, 100, 100));
camera->lookAt(Vec3(0, 0, 0), Vec3(0, 1, 0));
gameLayer->addChild(camera); //add camera to the scene
// You'll get a NULL camera inside BillBoard::calculateBillbaordTransform() function
// if you call visit()
/*auto billboard = BillBoard::create("cocos2d-x.png", BillBoard::Mode::VIEW_POINT_ORIENTED);
billboard->setPosition(Vec2(VisibleRect::center().x, VisibleRect::center().y));
gameLayer->addChild(billboard, 100);*/
// This one won't render into the texture
Sprite3D* sprite3D = Sprite3D::create("blend_test/character_3_animations_test.c3b");
sprite3D->setScale(5.0f); //sets the object scale in float
sprite3D->setRotation3D(Vec3(0.0f, 0.0f, 0.0f));
//sprite3D->setPosition3D(Vec3(VisibleRect::center().x, VisibleRect::center().y, 0.0f)); //sets sprite position
sprite3D->setPosition(Vec2(VisibleRect::center().x, VisibleRect::center().y));
gameLayer->addChild(sprite3D, 1); //adds sprite to scene, z-index: 1
// This one works just fine and appears black and white as expected
// in the resulting texture
Sprite* sprite2D = Sprite::create("cocos2d-x.png");
sprite2D->setPosition(Vec2(VisibleRect::center().x, VisibleRect::center().y));
gameLayer->addChild(sprite2D);
// Black and white OpenGL shader
GLProgram* glProgram = GLProgram::createWithFilenames("shaders/gray.vert", "shaders/gray.frag");
glProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_POSITION);
glProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_COLOR);
glProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORD);
glProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD1, GLProgram::VERTEX_ATTRIB_TEX_COORD1);
glProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD2, GLProgram::VERTEX_ATTRIB_TEX_COORD2);
glProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD3, GLProgram::VERTEX_ATTRIB_TEX_COORD3);
glProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_NORMAL, GLProgram::VERTEX_ATTRIB_NORMAL);
glProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_BLEND_WEIGHT, GLProgram::VERTEX_ATTRIB_BLEND_WEIGHT);
glProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_BLEND_INDEX, GLProgram::VERTEX_ATTRIB_BLEND_INDEX);
glProgram->link();
glProgram->updateUniforms();
RenderTexture* renderTexture = RenderTexture::create(VisibleRect::width(), VisibleRect::height());
renderTexture->retain();
Sprite* ppSprite = Sprite::createWithTexture(renderTexture->getSprite()->getTexture());
ppSprite->setTextureRect(Rect(0, 0, ppSprite->getTexture()->getContentSize().width,
ppSprite->getTexture()->getContentSize().height));
ppSprite->setAnchorPoint(Point::ZERO);
ppSprite->setPosition(Point::ZERO);
ppSprite->setFlippedY(true);
ppSprite->setGLProgram(glProgram);
this->addChild(ppSprite, 100);
renderTexture->beginWithClear(0.0f, 0.0f, 0.0f, 0.0f);
auto renderer = _director->getRenderer();
auto& parentTransform = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
gameLayer->visit(renderer, parentTransform, true);
//gameLayer->visit();
renderTexture->end();
ppSprite->setTexture(renderTexture->getSprite()->getTexture());
Cocos2d-x v3.11.1 (current as of this post) and below don't properly support RenderTextures with Sprite3D because of a clear depth buffer bug.
There is a GitHub issue on the bug. But a workaround now exists:
...
sprite3D->setForce2DQueue(true); // puts your Sprite3D on same render queue as the RenderTexture. More info below.
...
auto rt = RenderTexture::create(1280, 720, Texture2D::PixelFormat::RGBA8888, GL_DEPTH24_STENCIL8); // By default a depth buffer isn't created
rt->setKeepMatrix(true); // required
...
...
rt->beginWithClear(0, 0, 0, 0, 1); // required, clears the depth buffer
Also, changes need to be made to RenderTexture.cpp. This fixes the clear depth buffer bug in Cocos2d-x.
void RenderTexture::onClear()
{
// save clear color
GLfloat oldClearColor[4] = {0.0f};
GLfloat oldDepthClearValue = 0.0f;
GLint oldStencilClearValue = 0;
GLboolean oldDepthWrite = GL_FALSE;
// backup and set
if (_clearFlags & GL_COLOR_BUFFER_BIT)
{
glGetFloatv(GL_COLOR_CLEAR_VALUE, oldClearColor);
glClearColor(_clearColor.r, _clearColor.g, _clearColor.b, _clearColor.a);
}
if (_clearFlags & GL_DEPTH_BUFFER_BIT)
{
glGetFloatv(GL_DEPTH_CLEAR_VALUE, &oldDepthClearValue);
glClearDepth(_clearDepth);
glGetBooleanv(GL_DEPTH_WRITEMASK, &oldDepthWrite);
glDepthMask(true);
}
if (_clearFlags & GL_STENCIL_BUFFER_BIT)
{
glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &oldStencilClearValue);
glClearStencil(_clearStencil);
}
// clear
glClear(_clearFlags);
// restore
if (_clearFlags & GL_COLOR_BUFFER_BIT)
{
glClearColor(oldClearColor[0], oldClearColor[1], oldClearColor[2], oldClearColor[3]);
}
if (_clearFlags & GL_DEPTH_BUFFER_BIT)
{
glClearDepth(oldDepthClearValue);
glDepthMask(oldDepthWrite);
}
if (_clearFlags & GL_STENCIL_BUFFER_BIT)
{
glClearStencil(oldStencilClearValue);
}
}
See the issue for more details. I also made an example gist of the workaround. Screenshot below.
I'm not sure about billboards, but this workaround might fix it too.
Info on Cocos2d-x render queues:
The Sprite3D needs to be on the same render queue as the RenderTexture. Cocos2d-x (as of v3.7 or so) now has 5 render queues:
Global Z Order < 0
3D Opaque
3D Transparent
Global Z Order == 0 (default for 2D)
Global Z Order > 0
You can put the Sprite3D and the RenderTexture on the last queue with setGlobalZOrder(1) or just put the Sprite3D in the 2D queue with sprite3D->setForce2DQueue(true).
unlike cocos2d RenderTexture the following worked fine for 3D screen capture (or anything i imagine)!
Sprite * CcGlobal::getScreenAsSprite(void) {
Size screenSize = Director::getInstance()->getWinSize();
int width = screenSize.width;
int height = screenSize.height;
std::shared_ptr<GLubyte> buffer(new GLubyte[width * height * 4], [](GLubyte* p) { CC_SAFE_DELETE_ARRAY(p); });
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer.get());
Image* image = new (std::nothrow) Image;
image->initWithRawData(buffer.get(), width * height * 4, width, height, 8);
Texture2D *texture = new (std::nothrow) Texture2D();
texture->initWithImage(image);
SpriteFrame *spriteFrame = SpriteFrame::createWithTexture(texture, Rect(Vec2(0, 0), screenSize));
Sprite *sprite = Sprite::createWithSpriteFrame(spriteFrame);
sprite->setFlippedY(true);
delete image;
return sprite;
}
===================================================
I want to move a sprite (which happens to be a Rectangle) from any position of the screen and make it stop at exactly the touched position of the screen. Now, I can stop my sprite already, but not at the exact touched position. I cannot find a good way of doing this without sacrificing either accuracy or risking the sprite to not stop at all.
Naturally - the problem arises because the current position is Float, so that Vector will never (or extremely rarely) have the exact same coordinates as the touch point (which is an int).
In the code below, I stop my sprite by simply checking the distance between the current position and the target position (i.e. the touched position Vector3), like so if (touch.dst(currentPsition.x, currentPosition.y, 0) < 4).
For example, if the sprite is at position (5,5) and I touch the screen at (100,100), it will stop at like (98.5352,96.8283).
My question is, how do I stop the sprite at exactly the touch position, without having to approximate?
void updateMotion() {
if (moveT) {
movement.set(velocity).scl(Gdx.graphics.getDeltaTime());
this.setPosition(currentPosition.add(movement));
if (touch.dst(currentPosition.x, currentPosition.y, 0) < 4)
moveT = false;
}
}
public void setMoveToTouchPosition(boolean moveT) {
this.moveT = moveT;
this.touch = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
GameScreen.getCamera().unproject(touch);
currentPosition = new Vector2(this.x, this.y);
direction.set(new Vector2(touch.x, touch.y)).sub(currentPosition).nor();
velocity = new Vector2(direction).scl(speed);
}
Of course sprite can't move smoothly to touch position and then stop in exactly the same position because of many reasons. Just change this
if (touch.dst(currentPosition.x, currentPosition.y, 0) < 4)
moveT = false;
to this
if (touch.dst(currentPosition.x, currentPosition.y, 0) < 2) {
currentPosition.x = touch.x;
currentPosition.y = touch.y;
moveT = false;
}
A quick yet acceptable solution to this could be the use of the Rectangle class. Considering you make a Rectangle surrounding the moving entity and constantly update it's bounds based on its current location, it's texture width, and it's texture height. You could stop it when it overlaps with the "target position". If you do this you guarantee yourself that it will stop exactly at that position. For example:
Texture entityTexture = new Texture("assets/image.png");
Rectangle entityBounds = new Rectangle();
entityBounds.set((currentPosition.x, currentPosition.y, entityTexture .getWidth(), entityTexture .getHeight()));
Rectangle targetBounds = new Rectangle();
targetBounds.set((targetPosition.x, targetPosition.y, 1, 1)); // make width and height 1 by 1 for max accuracy
public void update(){
// update bounds based on new position
entityBounds.set((currentPosition.x, currentPosition.y, entityTexture.getWidth(), entityTexture.getHeight()));
targetBounds.set((targetPosition.x, targetPosition.y, 1, 1));
if(entityBounds.overlaps(targetBounds)){
// do something
}
}
I need to flip a card to see its back, then side and then front gradually with animation like this: https://www.youtube.com/watch?v=te0Je0y4zU0 . How I can do this with cocos2d-x? I have took a look on OrbitCamera and RotateBy in 3D tests. They are very close to the one I want to, the only problem is that when the sprite turns around I see not the back (as at should be another texture, but the same spite from back camera). I understand that I should use 2 sprites to get the effect, but how I should do that, I don't know. Should I position 2 sprite with different Z order? Please advice.
Try this:
float duration = 2.0f;
auto actionBy = RotateBy::create(duration / 2, Vec3(0, 90, 0));
backCard->runAction(RotateBy::create(0, Vec3(0, 90, 0)));
frontCard->runAction( Sequence::create(
actionBy,
CallFunc::create([backCard, actionBy](){backCard->runAction(actionBy);}),
nullptr)
you need to simply do this :
CCRotateTo *act1= CCRotateTo::create(0.5, -180);
CCRotateTo *act2= CCRotateTo::create(1.0, 180);
CCSequence* act3 = CCSequence::create(act1,act2,NULL);
sprite->runAction(act3);
you should view https://www.youtube.com/watch?v=Q4fJrMvZVhI
same with cocos2dx using javascript.
reveal: function (pIsFaceUp) {
let self = this;
let timeFlip =0.5;
let callFunc = cc.callFunc(function () {
self.cardBG.spriteFrame = pIsFaceUp ? self.texFrontBG : self.texBackBG;
self.point.node.active = pIsFaceUp;
self.suit.node.active = pIsFaceUp;
self.mainPic.node.active = pIsFaceUp;
if(!pIsFaceUp)
self.node.skewY=135;
else
self.node.skewY=45;
});
if(!pIsFaceUp)
{
self.node.skewY=0;
let action = cc.skewBy(timeFlip/2,0,45);
let action2 = cc.skewTo(timeFlip/2,0,180);
self.node.runAction(cc.sequence(action,callFunc,action2));
}else
{
self.node.skewY=180;
let action = cc.skewBy(timeFlip/2,0,-45);
let action2 = cc.skewTo(timeFlip/2,0,0);
self.node.runAction(cc.sequence(action,callFunc,action2));
}
},
Use 2 Sprites: spriteFront, spriteBack
init (show spriteBack at first):
scale spriteFront to (0, 1) (scale X to 0, while keeping scale Y to 1)
scale spriteBack to (1, 1)
flip animation:
scale spriteBack to (0, 1)
after the animation,
scale spriteFront to (1, 1)
float fDuration = 0.8f;
CCArray* pArray = CCArray::create();
pArray->addObject(CCScaleTo::create(fDuration/2, 0, 1));
pArray->addObject(CCTargetedAction::create(spriteFront, CCScaleTo::create(fDuration/2, 1)));
CCFiniteTimeAction* flipCardAnimation = CCSequence::create(pArray);
spriteBack->runAction(flipCardAnimation);
I started to build a run game app for Android. I chose to make it in flash using tiles and Adobe Air. The game is that a player should run automatically to the right and avoid some obstacles by jumping or sliding along the ground.
I have made a function which always takes the first level in the array and uses as the starting level.
private function createLevel()
{
map_level.levell();
level = map_level.level1;
for(var t = 0; t < level.length; t++)
{
for(var u = 0; u < level[t].length; u++)
{
if(level[t][u] != 0)
{
var new_tile:platform_tile = new platform_tile;
addChild(new_tile);
new_tile.gotoAndStop(level[t][u]);
new_tile.x = u * 32;
new_tile.y = t * 32;
tiles.push(new_tile);
}
}
}
total_tile_width += u;
}
Then I create a function that takes a random level in the array of paths.
private function random_level ()
This level is then added at the end of the first track when the player has reached a certain length along the track, then the track seems endless and then made such that the camera follows the player.
private function update_level ()
{
random_level();
for(var t = 0; t < mid_lvl.length; t++)
{
for(u = 0; u < mid_lvl[t].length; u++)
{
if(mid_lvl[t][u] != 0)
{
var new_tile:platform_tile = new platform_tile;
level[t][u + total_tile_width] = mid_lvl[t][u];
addChild(new_tile);
new_tile.gotoAndStop(mid_lvl[t][u]);
new_tile.x = (u + total_tile_width) * 32;
new_tile.y = t * 32;
tiles.push(new_tile);
}
}
}
// Indstiller hvis spilleren skal have en stigende fart
if( movementspeed < 40)
{
movementspeed = movementspeed + 2;
}
else
movementspeed = movementspeed;
total_tile_width += u;
trace ("speed: " + movementspeed);
}
All this works as it should and game function also perfect as a PC, but the phone seems quick to overload it, since I can not figure out how to remove the old levels that have already been played and therefore there's going to be a lot levels in the phone memory.
I need to something like removeChild("old tiles the left the stage again) but got no idear how to only find the tiles that old and not just all tiles.
Anyone able to help me? btw hope you understand my question as im not the best at writing english.
Morten
You must use 2 BitmapData objects.
2 are the size of the screen. We call them screenBuffer1 and screenBuffer2
the other is larger than the screen by at least the width of a tile. We call it terrainBuffer
Then :
Init the terrainBuffer by drawing all visible tiles of the start screen
Copy the currently visible area on screenBuffer1
Draw sprites on screenBuffer1
Attach screenBuffer1 to stage
Now we start scrolling
Copy the currently visible area on screenBuffer2, offset by scroll amount
Draw sprites on screenBuffer2
Attach screenBuffer2 to stage
Continue increasing offset and alternate screenBuffer1 and screenBuffer2 so one is visible while you draw on the other
When offset reach the witdh of a tile :
if(offset>tileWidth){
offset-=tileWidth;
// Move content of terrainBuffer to the left by tileWidth pixels
// Draw a new column of tile on the right
}
Then keep on looping !
Is it possible to fade the alpha with a soft wipe transition using as3 tween?
I thought maybe http://www.greensock.com might have the answer but I have found nothing. I would like the image to slowly fade away from one side to the other. A soft dissolve.
I thought maybe its possible using a mask but I don't think masks accept alphas otherwise it could be done that way.
Actually masks allow alphas. It's kind of a hack. You should try writing this in code:
maskMC.cacheAsBitmap = true;
objMC.cacheAsBitmap = true;
objMC.mask = maskMC;
Where objMC is your animated MovieClip and maskMC is your Mask that contains a gradient shape with transparency. See an example here: Link
You can also achieve this effect using Greensock. Code would look like this:
TweenLite.to(objMC, 1, {"alpha":0, "x":objMC.x + 10});
When using TweenLite, you need to provide object to animate, duration of animation and an instance of an Object class (that's stuff we write between curly braces). This instance contains all the values we want to change gradually.
You can accomplish this by using the ALPHA blendmode.
Make a shape that has a gradient whose alpha goes from full to nothing, then make it's blend mode ALPHA, put it in the same container as your item you wish to mask.
Then set the container blendmode to LAYER
Psuedo Code:
container.blendMode = BlendMode.LAYER; //container holds both the mask and the thing you want masked
maskObj.blendMode = BlendMode.ALPHA;
drawMaskGradients();
Here is a function I've used in the past to create said mask via code: (itemContainer is the object I'm masking)
You could however do this all in the Flash IDE using design tools.
softMaskSprite = new Sprite();
this.blendMode = BlendMode.LAYER;
softMaskSprite.blendMode = BlendMode.ALPHA;
softMaskSprite.mouseChildren = false;
softMaskSprite.mouseEnabled = false;
this.addChildAt(softMaskSprite,this.getChildIndex(itemContainer)+1);
//Create Sides
var top:Shape = new Shape();
var matr:Matrix = new Matrix();
matr.createGradientBox(areaWidth + (softMaskWidth * 2), softMaskWidth, 90 * (Math.PI / 180), 0, 0);
top.graphics.beginGradientFill(GradientType.LINEAR, [0xFF0000, 0x0000FF], [0,1], [0,255], matr, SpreadMethod.PAD);
top.graphics.drawRect(0, 0, areaWidth + (softMaskWidth * 2), softMaskWidth);
top.graphics.endFill();
top.x = softMaskWidth * -1;
top.y = softMaskWidth * -1;
softMaskSprite.addChild(top);
//BOTTOM
var bottom:Shape = new Shape();
matr = new Matrix();
matr.createGradientBox(areaWidth + (softMaskWidth * 2), softMaskWidth, 90 * (Math.PI / 180), 0, 0);
bottom.graphics.beginGradientFill(GradientType.LINEAR, [0xFF0000, 0x0000FF], [1,0], [0,255], matr, SpreadMethod.PAD);
bottom.graphics.drawRect(0, 0, areaWidth + (softMaskWidth * 2), softMaskWidth);
bottom.graphics.endFill();
bottom.y = areaHeight;
bottom.x = softMaskWidth * -1;
softMaskSprite.addChild(bottom);