Search Results

Search found 67 results on 3 pages for 'spritesheet'.

Page 3/3 | < Previous Page | 1 2 3 

  • Tile engine Texture not updating when numbers in array change

    - by Corey
    I draw my map from a txt file. I am using java with slick2d library. When I print the array the number changes in the array, but the texture doesn't change. public class Tiles { public Image[] tiles = new Image[5]; public int[][] map = new int[64][64]; public Image grass, dirt, fence, mound; private SpriteSheet tileSheet; public int tileWidth = 32; public int tileHeight = 32; public void init() throws IOException, SlickException { tileSheet = new SpriteSheet("assets/tiles.png", tileWidth, tileHeight); grass = tileSheet.getSprite(0, 0); dirt = tileSheet.getSprite(7, 7); fence = tileSheet.getSprite(2, 0); mound = tileSheet.getSprite(2, 6); tiles[0] = grass; tiles[1] = dirt; tiles[2] = fence; tiles[3] = mound; int x=0, y=0; BufferedReader in = new BufferedReader(new FileReader("assets/map.dat")); String line; while ((line = in.readLine()) != null) { String[] values = line.split(","); x = 0; for (String str : values) { int str_int = Integer.parseInt(str); map[x][y]=str_int; //System.out.print(map[x][y] + " "); x++; } //System.out.println(""); y++; } in.close(); } public void update(GameContainer gc) { } public void render(GameContainer gc) { for(int y = 0; y < map.length; y++) { for(int x = 0; x < map[0].length; x ++) { int textureIndex = map[x][y]; Image texture = tiles[textureIndex]; texture.draw(x*tileWidth,y*tileHeight); } } } } Mouse Picking Where I change the number in the array Input input = gc.getInput(); gc.getInput().setOffset(cameraX-400, cameraY-300); float mouseX = input.getMouseX(); float mouseY = input.getMouseY(); double mousetileX = Math.floor((double)mouseX/tiles.tileWidth); double mousetileY = Math.floor((double)mouseY/tiles.tileHeight); double playertileX = Math.floor(playerX/tiles.tileWidth); double playertileY = Math.floor(playerY/tiles.tileHeight); double lengthX = Math.abs((float)playertileX - mousetileX); double lengthY = Math.abs((float)playertileY - mousetileY); double distance = Math.sqrt((lengthX*lengthX)+(lengthY*lengthY)); if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON) && distance < 4) { System.out.println("Clicked"); if(tiles.map[(int)mousetileX][(int)mousetileY] == 1) { tiles.map[(int)mousetileX][(int)mousetileY] = 0; } } I never ask a question until I have tried to figure it out myself. I have been stuck with this problem for two weeks. It's not like this site is made for asking questions or anything. So if you actually try to help me instead of telling me to use a debugger thank you. You either get told you have too much or too little code. Nothing is never enough for the people on here it's as bad as something like reddit. Idk what is wrong all my textures work when I render them it just doesn't update when the number in the array changes. I am obviously debugging when I say that I was printing the array and the number is changing like it should, so it's not a problem with my mouse picking code. It is a problem with my textures, but I don't know what because they all render correctly. That is why I need help.

    Read the article

  • Java - Tile engine changing number in array not changing texture

    - by Corey
    I draw my map from a txt file. Would I have to write to the text file to notice the changes I made? Right now it changes the number in the array but the tile texture doesn't change. Do I have to do more than just change the number in the array? public class Tiles { public Image[] tiles = new Image[5]; public int[][] map = new int[64][64]; private Image grass, dirt, fence, mound; private SpriteSheet tileSheet; public int tileWidth = 32; public int tileHeight = 32; Player player = new Player(); public void init() throws IOException, SlickException { tileSheet = new SpriteSheet("assets/tiles.png", tileWidth, tileHeight); grass = tileSheet.getSprite(0, 0); dirt = tileSheet.getSprite(7, 7); fence = tileSheet.getSprite(2, 0); mound = tileSheet.getSprite(2, 6); tiles[0] = grass; tiles[1] = dirt; tiles[2] = fence; tiles[3] = mound; int x=0, y=0; BufferedReader in = new BufferedReader(new FileReader("assets/map.dat")); String line; while ((line = in.readLine()) != null) { String[] values = line.split(","); for (String str : values) { int str_int = Integer.parseInt(str); map[x][y]=str_int; //System.out.print(map[x][y] + " "); y=y+1; } //System.out.println(""); x=x+1; y = 0; } in.close(); } public void update(GameContainer gc) { } public void render(GameContainer gc) { for(int x = 0; x < map.length; x++) { for(int y = 0; y < map.length; y ++) { int textureIndex = map[y][x]; Image texture = tiles[textureIndex]; texture.draw(x*tileWidth,y*tileHeight); } } } Mouse picking public void checkDistance(GameContainer gc) { Input input = gc.getInput(); float mouseX = input.getMouseX(); float mouseY = input.getMouseY(); double mousetileX = Math.floor((double)mouseX/tiles.tileWidth); double mousetileY = Math.floor((double)mouseY/tiles.tileHeight); double playertileX = Math.floor(playerX/tiles.tileWidth); double playertileY = Math.floor(playerY/tiles.tileHeight); double lengthX = Math.abs((float)playertileX - mousetileX); double lengthY = Math.abs((float)playertileY - mousetileY); double distance = Math.sqrt((lengthX*lengthX)+(lengthY*lengthY)); if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON) && distance < 4) { System.out.println("Clicked"); if(tiles.map[(int)mousetileX][(int)mousetileY] == 1) { tiles.map[(int)mousetileX][(int)mousetileY] = 0; } } System.out.println(tiles.map[(int)mousetileX][(int)mousetileY]); }

    Read the article

  • XNA Notes 011

    - by George Clingerman
    Even with a lot of the XNA community working on Dream Build Play entries ( I swear I’m going to finish mine this year!) people are still finding time to do side projects and be amazingly active in the XNA and XBLIG community. With my one eye on my code and one eye on the community, here’s what I noticed these over achievers doing this past week! Time Critical XNA News: Xbox LIVE Indie Games sales data will be delayed March 17-20th due to some schedule maintenance http://create.msdn.com/en-us/news/indie_games_data_delay_march2011 GameMarx is releasing a series of videos to help raise donations for victims of the earthquakes and tsunami in Japan. Help out if you can! http://www.gamemarx.com/video/special/29/help-japan-sushido.aspx XNA MVPs: Catalin Zima shares his thoughts on the MVP summit and my book! http://www.catalinzima.com/2011/03/mvp-summit-2011/ Glenn Wilson (@mykre) helps the XNA team announce some new educational content that you don’t want to miss if you’re porting your app or game to Windows Phone 7 http://www.virtualrealm.com.au/Blog/tabid/62/EntryId/653/Porting-your-App-or-Game-to-Windows-Phone-7.aspx and Windows Phone 7 from scratch http://www.virtualrealm.com.au/Blog/tabid/62/EntryId/654/Windows-Phone-from-Scratch.aspx and shares a link to some free architectural models and textures http://twitter.com/#!/Mykre/status/46410160784158720 George (that’s me!) shares his MVP Summit 2011 summary and XBLIG thoughts http://geekswithblogs.net/clingermangw/archive/2011/03/15/144366.aspx XNA Developers: @SmallCaveGames shares a Code of Ethics for Xbox LIVE Indie Game Developers http://smallcavegames.blogspot.com/2011/03/unofficial-xblig-developers-code-of.html Derek S adds more Xbox LIVE Indie Game studios to his master list of XBLIG links http://twitter.com/#!/Mr_Deeke/status/46140996056125440 http://xbl-indieverse.blogspot.com/p/xblig-links.html Making games and want to help kids? Then share your story with GameFace: America! http://gameitupinitiative.com/about-the-initiative/programs/gameface-america/ Xbox LIVE Indie Games (XBLIG): XonaGames shares some video footage of their booth from GDC 2011 Video 1: http://youtu.be/lxIV9nk3Gq4 Video 2: http://youtu.be/GgfrjqkxR_o Video 3: http://youtu.be/yVcpXrTX7SQ Joystiq on Mommy’s Best Games Serious Sam Double D http://www.joystiq.com/2011/03/16/the-most-important-thing-about-serious-sam-double-d/ And The Escapist recommends that gamers start learning to avoid cleavage now http://www.escapistmagazine.com/news/view/108543-Boobie-Bomber-Makes-First-Appearance-in-Serious-Sam-Double-D Magiko Gaming started a blog on the XBLIG dashboard daily Top 10 games in the US. Good way to go back in time and look at the history of which games were in the the Top 10. http://dailytop10indiegames.wordpress.com/ Where are they going now? XBLIG developers at a crossroads.. http://www.gamesetwatch.com/2011/03/where_are_they_going_now_xblig.php http://www.gamasutra.com/view/news/33527/InDepth_Where_Are_They_Going_Now_XBLIG_Developers_At_A_Crossroads_.php BinaryTweed’s Clover: A Curious Tail is Xbox LIVE’s Deal of the Week! http://www.armlessoctopus.com/2011/03/15/what-luck-clover-a-curious-tale-is-half-price-this-week/ Looking for an Xbox LIVE Indie Game to buy? Writings of Mass Deduction has over 125 suggestions at this point! http://writingsofmassdeduction.com/ SkaStudios shares Vampire Smile Achievements AND their PAX East 2011 Both Setup video http://www.ska-studios.com/2011/03/14/vampire-smile-achievement/ http://www.ska-studios.com/2011/03/15/pax-booth-setup-time-lapse/ MasterBlud and VVGTV starts a new community for XBLIG developers and gamers to join http://vvgtv.forumotion.com/ Raymond Matthews (@DrakstarMatryx) covers Mommy’s Best Games getting Serious http://www.darkstarmatryx.com/?p=286 XNA Development: Dave Henry (@mort8088) posts the 4th tutorial in his series XNA 4.0 SpriteBatch extended http://mort8088.com/2011/03/11/xna-4-0-tutorial-4-spritebatch-extended/ Tutorial 5 - Creating a manual blank texture http://mort8088.com/2011/03/13/xna-4-tutorial-5-manual-blank-texture/ XNA 4.0 Tutorial 6 - Spritesheet Object http://mort8088.com/2011/03/18/xna-4-0-tutorial-6-spritesheet-object/ Jason Mitchell shares a tutorial on setting the alpha value for spritebatch in XNA 4.0 http://www.jason-mitchell.com/index.php/2011/03/13/setting-alpha-value-for-spritebatch-draw-in-xna-4/ XNA for Silverlight Developers: Part 7 - Collision Detection http://www.silverlightshow.net/items/XNA-for-Silverlight-developers-Part-7-Collision-detection.aspx Markus Ewald (@Cygon4) shares the full Ninject 2.0 binding for XNA and Sunburn http://twitter.com/#!/Cygon4/status/48330203826622464 Michael B. McLaughlin shares an AccelerometerInput XNA GameComponent he created (which I’m probably going to snag for a game I’m working on...) http://geekswithblogs.net/mikebmcl/archive/2011/03/17/accelerometerinput-xna-gamecomponent.aspx Extra Credit tackles the building of a good tutorial. Must watch for all Indie game devs (thanks for pointing it out Evan Johnson!) http://twitter.com/#!/johnsonevan/status/48452115680604160 http://www.escapistmagazine.com/videos/view/extra-credits/2921-Tutorials-101 ExEn is fully funded at this point so definitely something for XBLIG developers to keep an eye on as they consider releasing their games on other platforms http://rockethub.com/projects/752-exen-xna-for-iphone-android-and-silverlight Channel 9 and Greg Duncan post Mixing the Game State Management and Platformer XNA Recipes http://channel9.msdn.com/coding4fun/blog/Mixing-the-Game-State-Management-and-Platformer-XNA-Recipes Sgt. Conker has noticed Mike McLaughlin has been crazy productive and has done a recap of his recent posts http://www.sgtconker.com/2011/03/recap-of-mikebmcls-posts/

    Read the article

  • Loading Texture2D is extremly slow on XBOX360

    - by AvrDragon
    I have ~100 sprites for each level im my XNA game. On windows it takes ~2 seconds to load them all. Unfortunately on XBOX360 it takes ~30-60 seconds. Am i doing something wrong? Essentially the loading code ist just like this: Texture2D sprite1 = levelContent.Load<Texture2D>("images/level_1/my_sprite_1"); ... Texture2D sprite100 = levelContent.Load<Texture2D>("images/level_1/my_sprite_100"); (i use an own content manager for each level to release all level-specific textures at once) Of course i can reduse the ammount of sprites using a spritesheet, but it's extremly painfull for me now. Do i have a better option? And just curious - why is there such huge difference in image loading time?

    Read the article

  • Animate sprite/texture position with VBO

    - by Dono
    I'm currently worlking on a renderer for my projects and I want animate a sprite on screen. I've got a spritesheet but I don't know what is the the best way to update the texture coordinates for each vertex. Update vertices then update vertex buffer. (Heavy ?) Send to the shader my texture coordinates (It is possible ?) Don't use VBO ? By the way, I've got this structure : Object class with Geometry (Faces + Vertex + Buffer) and Material (Shader + other stuff ) properties, it is a good structure ? Thanks!

    Read the article

  • Stuck in Infinite Loop while PostInvalidating

    - by Nicholas Roge
    I'm trying to test something, however, the loop I'm using keeps getting stuck while running. It's just a basic lock thread while doing something else before continuing kind of loop. I've double checked that I'm locking AND unlocking the variable I'm using, but regardless it's still stuck in the loop. Here are the segments of code I have that cause the problem: ActualGame.java: Thread thread=new Thread("Dialogue Thread"){ @Override public void run(){ Timer fireTimer=new Timer(); int arrowSequence=0; gameHandler.setOnTouchListener( new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent me) { //Do something. if(!gameHandler.fireTimer.getActive()){ exitLoop=true; } return false; } } ); while(!exitLoop){ while(fireTimer.getActive()||!gameHandler.drawn); c.drawBitmap(SpriteSheet.createSingleBitmap(getResources(), R.drawable.dialogue_box,240,48),-48,0,null); c.drawBitmap(SpriteSheet.createSingleBitmap(getResources(),R.drawable.dialogue_continuearrow,32,16,8,16,arrowSequence,0),-16,8,null); gameHandler.drawn=false; gameHandler.postInvalidate(); if(arrowSequence+1==4){ arrowSequence=0; exitLoop=true; }else{ arrowSequence++; } fireTimer.startWait(100); } gameHandler.setOnTouchListener(gameHandler.defaultOnTouchListener); } }; thread.run(); And the onDraw method of GameHandler: canvas.scale(scale,scale); canvas.translate(((screenWidth/2)-((terrainWidth*scale)/2))/scale,((screenHeight/2)-((terrainHeight*scale)/2))/scale); canvas.drawColor(Color.BLACK); for(int layer=0;layer(less than)tiles.length;layer++){ if(layer==playerLayer){ canvas.drawBitmap(playerSprite.getCurrentSprite(), playerSprite.getPixelLocationX(), playerSprite.getPixelLocationY(), null); continue; } for(int y=0;y(less than)tiles[layer].length;y++){ for(int x=0;x(less than)tiles[layer][y].length;x++){ if(layer==0&&tiles[layer][y][x]==null){ tiles[layer][y][x]=nullTile; } if(tiles[layer][y][x]!=null){ runningFromTileEvent=false; canvas.drawBitmap(tiles[layer][y][x].associatedSprite.getCurrentSprite(),x*tiles[layer][y][x].associatedSprite.spriteWidth,y*tiles[layer][y][x].associatedSprite.spriteHeight,null); } } } } for(int i=0;i(less than)canvasEvents.size();i++){ if(canvasEvents.elementAt(i).condition(this)){ canvasEvents.elementAt(i).run(canvas,this); } } Log.e("JapaneseTutor","Got here.[1]"); drawn=true; Log.e("JapaneseTutor","Got here.[2]"); If you need to see the Timer class, or the full length of the GameHandler or ActualGame classes, just let me know.

    Read the article

  • How can I make OpenGL textures scale without becoming blurry?

    - by adorablepuppy
    I'm using OpenGL through LWJGL. I have a 16x16 textured quad rendering at 16x16. When I change it's scale amount, the quad grows, then becomes blurrier as it gets larger. How can I make it scale without becoming blurry, like in Minecraft. Here is the code inside my RenderableEntity object: public void render(){ Color.white.bind(); this.spriteSheet.bind(); GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(0,0); GL11.glVertex2f(this.x, this.y); GL11.glTexCoord2f(1,0); GL11.glVertex2f(getDrawingWidth(), this.y); GL11.glTexCoord2f(1,1); GL11.glVertex2f(getDrawingWidth(), getDrawingHeight()); GL11.glTexCoord2f(0,1); GL11.glVertex2f(this.x, getDrawingHeight()); GL11.glEnd(); } And here is code from my initGL method in my game class GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glClearColor(0.46f,0.46f,0.90f,1.0f); GL11.glViewport(0,0,width,height); GL11.glOrtho(0,width,height,0,1,-1); And here is the code that does the actual drawing public void start(){ initGL(800,600); init(); while(true){ GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); for(int i=0;i<entities.size();i++){ ((RenderableEntity)entities.get(i)).render(); } Display.update(); Display.sync(100); if(Display.isCloseRequested()){ Display.destroy(); System.exit(0); } } }

    Read the article

  • Dealing with "jumping" sprites: badly centered?

    - by GigaBass
    Thing is, I've used darkFunction Editor as a way to get all the spriteCoordinates off a spriteSheet for each individual sprite, and parse the .xml it generates inside my game. It all works fine, except when the sprites are all similarly sized, but when a sprite changes from a small sprite into a big one, such as here: When from walking from some direction, to attacking, it starts "jumping", appearing glitchy, because it's not staying in the same correct position, only doing so for the right attacking sprite, due to the drawing being made from the lower left part of the rectangle. I think someone experienced will immediately recognize the problem I mean, if not, when I return home soon, I will shoot a little youtube video demonstrating the issue! So the question is: what possible solutions are there? I've thought that some sort of individual frame "offset" system might be the answer, or perhaps splitting, in this case, the sprite in 2: the sword, and the character itself, and draw sword according to character's facing, but that might be overly complex. Another speculation would be that there might be some sort of method in LibGdx, the library I'm using, that allows me to change the drawing center (which I looked for and didn't find), so I could choose from where the drawing starts.

    Read the article

  • 2D graphics - why use spritesheets?

    - by Columbo
    I have seen many examples of how to render sprites from a spritesheet but I havent grasped why it is the most common way of dealing with sprites in 2d games. I have started out with 2d sprite rendering in the few demo applications I've made by dealing with each animation frame for any given sprite type as its own texture - and this collection of textures is stored in a dictionary. This seems to work for me, and suits my workflow pretty well, as I tend to make my animations as gif/mng files and then extract the frames to individual pngs. Is there a noticeable performance advantage to rendering from a single sheet rather than from individual textures? With modern hardware that is capable of drawing millions of polygons to the screen a hundred times a second, does it even matter for my 2d games which just deal with a few dozen 50x100px rectangles? The implementation details of loading a texture into graphics memory and displaying it in XNA seems pretty abstracted. All I know is that textures are bound to the graphics device when they are loaded, then during the game loop, the textures get rendered in batches. So it's not clear to me whether my choice affects performance. I suspect that there are some very good reasons most 2d game developers seem to be using them, I just don't understand why.

    Read the article

  • Character creation using spritesheets

    - by Patrick Developer
    I am currently creating a 2D fighting game and have implemented a system where upon starting a new game, the player is presented with the option to create a custom character. I have a set of string arrays set with values that correspond to hair, headgear, chest, lower body and shoes. When done selecting a variety of items from the lists, a code is generated based off the index of each item (i.e 01123), which is then used to assign the correct Spritesheet to the player character. This has already presented a lot of work as I have had to create quite a few spreadsheets based of possible combinations, but I am now looking at a massive amount of work to implement each variation. I have started to look into setting layers for each item to reduce workload, but I am also looking at having different stances for the character - Depending on the currently equipped weapon - so this may present a lot of work either way. My question is, do I have any alternatives or am I stuck creating masses of Spritesheets to cover all combinations? As a side note, how much impact will assigning layered items have on overall performance?

    Read the article

  • Player sprite moving slower on iPhone 4

    - by nvillec
    I just finished getting movement/jump animation for a player sprite in Xcode using Cocos2D. The basic movement algorithm is a timer that updates every 0.01 sec, changing the sprite position to (sprite.position.x + xVel, sprite.position.y + yVel). Each time a movement button is tapped, the appropriate velocity (initialized to 0) is changed to whatever speed I choose, then a stop movement button returns the velocity to 0. It's not an ideal solution but I'm very new at this and stoked to at least have that working with little help from the internet. So I may not have explained that perfectly, but it is in fact working to my satisfaction in Xcode's iPhone Simulator, however when I build it for my device and run it on my phone, the sprite's movement speed is noticeably slower than in Xcode. At first I thought it must have to do with the resolution of the iPhone 4, making the sprite's movement path twice as long, but I found that if I pull up the multitask bar, then return to the app the speed will sometimes jump back to normal. My second theory was that the code is just inefficient and is bogging the processes down, but I would see this reflected in the frame rate wouldn't I? It stays at 59-60 the whole time, and the spritesheet animation runs at the correct speed. Has anyone experienced this? Is this a really obvious issue that I'm completely missing? Any help (or tips for optimizing my approach to movement) would be much appreciated!

    Read the article

  • How do you handle animations that are for transitioning between states?

    - by yaj786
    How does one usually handle animations that are for going between a game object's states? For example, imagine a very simple game in which a character can only crouch or stand normally. Currently, I use a custom Animation class like this: class Animation{ int numFrames; int curFrame; Bitmap spriteSheet; //... various functions for pausing, returning frame, etc. } and an example Character class class Character{ int state; Animation standAni; Animation crouchAni; //... etc, etc. } Thus, I use the state of the character to draw the necessary animation. if(state == STATE_STAND) draw(standAni.updateFrame()); else if(state == STATE_CROUCH) draw(crouchAni.updateFrame()); Now I've come to the point where I want to draw "in-between" animations, because right now the character will just jump immediately into a crouch instead of bending down. What is a good way to handle this? And if the way that I handle storing Animations in the Character class is not a good way, what is? I thought of creating states like STATE_STANDING_TO_CROUCHING but I feel like that may get messy fast.

    Read the article

  • Bitmapfontatlas cocos2d performance issue

    - by meboz
    This question was also asked in the cocos2d forums but they are a little slower than here. Hi, Im trying to resolve a performance issue in my game. I have all of my game images on the one spritesheet. I now have a score label for which i have generated a font file with the Hiero tool. Ideally I'd like to update my score label with the current score on every update. However there seems to be a significant performance hit when doing so, which i believe is the result of the game images texture and the font texture swapping each update. Can anyone suggest a way to avoid this? Possibly by combining the font images with the game images in the one image file to avoid the texture swapping? Cheers

    Read the article

  • How do I make this rendering thread run together with the main one?

    - by funk
    I'm developing an Android game and need to show an animation of an exploding bomb. It's a spritesheet with 1 row and 13 different images. Each image should be displayed in sequence, 200 ms apart. There is one Thread running for the entire game: package com.android.testgame; import android.graphics.Canvas; public class GameLoopThread extends Thread { static final long FPS = 10; // 10 Frames per Second private final GameView view; private boolean running = false; public GameLoopThread(GameView view) { this.view = view; } public void setRunning(boolean run) { running = run; } @Override public void run() { long ticksPS = 1000 / FPS; long startTime; long sleepTime; while (running) { Canvas c = null; startTime = System.currentTimeMillis(); try { c = view.getHolder().lockCanvas(); synchronized (view.getHolder()) { view.onDraw(c); } } finally { if (c != null) { view.getHolder().unlockCanvasAndPost(c); } } sleepTime = ticksPS - (System.currentTimeMillis() - startTime); try { if (sleepTime > 0) { sleep(sleepTime); } else { sleep(10); } } catch (Exception e) {} } } } As far as I know I would have to create a second Thread for the bomb. package com.android.testgame; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; public class Bomb { private final Bitmap bmp; private final int width; private final int height; private int currentFrame = 0; private static final int BMPROWS = 1; private static final int BMPCOLUMNS = 13; private int x = 0; private int y = 0; public Bomb(GameView gameView, Bitmap bmp) { this.width = bmp.getWidth() / BMPCOLUMNS; this.height = bmp.getHeight() / BMPROWS; this.bmp = bmp; x = 250; y = 250; } private void update() { currentFrame++; new BombThread().start(); } public void onDraw(Canvas canvas) { update(); int srcX = currentFrame * width; int srcY = height; Rect src = new Rect(srcX, srcY, srcX + width, srcY + height); Rect dst = new Rect(x, y, x + width, y + height); canvas.drawBitmap(bmp, src, dst, null); } class BombThread extends Thread { @Override public void run() { try { sleep(200); } catch(InterruptedException e){ } } } } The Threads would then have to run simultaneously. How do I do this?

    Read the article

  • Sprite animation in openGL - Some frames are being skipped

    - by Sid
    Earlier, I was facing problems on implementing sprite animation in openGL ES. Now its being sorted up. But the problem that i am facing now is that some of my frames are being skipped when a bullet(a circle) strikes on it. What I need : A sprite animation should stop at the last frame without skipping any frame. What I did : Collision Detection function and working properly. PS : Everything is working fine but i want to implement the animation in OPENGL ONLY. Canvas won't work in my case. ------------------------ EDIT----------------------- My sprite sheet. Consider the animation from Left to right and then from top to bottom Here is an image for a better understanding. My spritesheet ... class FragileSquare{ FloatBuffer fVertexBuffer, mTextureBuffer; ByteBuffer mColorBuff; ByteBuffer mIndexBuff; int[] textures = new int[1]; public boolean beingHitFromBall = false; int numberSprites = 20; int columnInt = 4; //number of columns as int float columnFloat = 4.0f; //number of columns as float float rowFloat = 5.0f; int oldIdx; public FragileSquare() { // TODO Auto-generated constructor stub float vertices [] = {-1.0f,1.0f, //byte index 0 1.0f, 1.0f, //byte index 1 //byte index 2 -1.0f, -1.0f, 1.0f,-1.0f}; //byte index 3 float textureCoord[] = { 0.0f,0.0f, 0.25f,0.0f, 0.0f,0.20f, 0.25f,0.20f }; byte indices[] = {0, 1, 2, 1, 2, 3 }; ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*2 * 4); // 4 vertices, 2 co-ordinates(x,y) 4 for converting in float byteBuffer.order(ByteOrder.nativeOrder()); fVertexBuffer = byteBuffer.asFloatBuffer(); fVertexBuffer.put(vertices); fVertexBuffer.position(0); ByteBuffer byteBuffer2 = ByteBuffer.allocateDirect(textureCoord.length * 4); byteBuffer2.order(ByteOrder.nativeOrder()); mTextureBuffer = byteBuffer2.asFloatBuffer(); mTextureBuffer.put(textureCoord); mTextureBuffer.position(0); } public void draw(GL10 gl){ gl.glFrontFace(GL11.GL_CW); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(1,GL10.GL_FLOAT, 0, fVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); if(MyRender.flag2==1){ /** Collision has taken place*/ int idx = oldIdx==(numberSprites-1) ? (numberSprites-1) : (int)((System.currentTimeMillis()%(200*numberSprites))/200); gl.glMatrixMode(GL10.GL_TEXTURE); gl.glTranslatef((idx%columnInt)/columnFloat, (idx/columnInt)/rowFloat, 0); gl.glMatrixMode(GL10.GL_MODELVIEW); oldIdx = idx; } gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); //4 gl.glTexCoordPointer(2, GL10.GL_FLOAT,0, mTextureBuffer); //5 gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); //7 gl.glFrontFace(GL11.GL_CCW); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glMatrixMode(GL10.GL_TEXTURE); gl.glLoadIdentity(); gl.glMatrixMode(GL10.GL_MODELVIEW); } public void loadFragileTexture(GL10 gl, Context context, int resource) { Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resource); gl.glGenTextures(1, textures, 0); gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); }

    Read the article

  • Deep Cloning C++ class that inherits CCNode in Cocos2dx

    - by A Devanney
    I stuck with something in Cocos2dx ... I'm trying to deep clone one of my classes that inherits CCNode. Basically i have.... GameItem* pTemp = new GameItem(*_actualItem); // loops through all the blocks in gameitem and updates their position pTemp->moveDown(); // if in boundary or collision etc... if (_gameBoard->isValidMove(pTemp)) { _actualItem = pTemp; // display the position CCLog("pos (1) --- (X : %d,Y : %d)", _actualItem->getGridX(),_actualItem->getGridY()); } Then doesn't work, because the gameitem inherits CCNode and has the collection of another class that also inherits CCNode. its just creating a shallow copy and when you look at children of the gameitem node in the copy, just point to the original? class GameItem : public CCNode { // maps to the actual grid position of the shape CCPoint* _rawPosition; // tracks the current grid position int _gridX, _gridY; // tracks the change if the item has moved CCPoint _offset; public: //constructors GameItem& operator=(const GameItem& item); GameItem(Shape shape); ... } then in the implementation.... GameItem& GameItem::operator=(const GameItem& item) { _gridX = item.getGridX(); _gridY = item.getGridY(); _offset = item.getOffSet(); _rawPosition = item.getRawPosition(); // how do i copy the node? return *this; } // shape contains an array of position for the game character GameItem::GameItem(Shape shape) { _rawPosition = shape.getShapePositions(); //loop through all blocks in position for (int i = 0; i < 7; i++) { // get the position of the first block in the shape and add to the position of the first block int x = (int) (getRawPosition()[i].x + getGridX()); int y = (int) (getRawPosition()[i].y + getGridY()); //instantiate a block with the position and type Block* block = Block::blockWithFile(x,y,(i+1), shape); // add the block to the this node this->addChild(block); } } And for clarity here is the block class class Block : public CCNode{ private: // using composition over inheritance CCSprite* _sprite; // tracks the current grid position int _gridX, _gridY; // used to store actual image number int _blockNo; public: Block(void); Block(int gridX, int gridY, int blockNo); Block& operator=(const Block& block); // static constructor for the creation of a block static Block* blockWithFile(int gridX, int gridY,int blockNo, Shape shape); ... } The blocks implementation..... Block& Block::operator=(const Block& block) { _sprite = new CCSprite(*block._sprite); _gridX = block._gridX; _gridY = block._gridY; _blockNo = block._blockNo; //again how to clone CCNode? return *this; } Block* Block::blockWithFile(int gridX, int gridY,int blockNo, Shape shape) { Block* block = new Block(); if (block && block->initBlockWithFile(gridX, gridY,blockNo, shape)) { block->autorelease(); return block; } CC_SAFE_DELETE(block); return NULL; } bool Block::initBlockWithFile(int gridX, int gridY,int blockNo, Shape shape) { setGridX(gridX); setGridY(gridY); setBlockNo(blockNo); const char* characterImg = helperFunctions::Format(shape.getFileName(),blockNo); // add to the spritesheet CCTexture2D* gameArtTexture = CCTextureCache::sharedTextureCache()->addImage("Character.pvr.ccz"); CCSpriteBatchNode::createWithTexture(gameArtTexture); // block settings _sprite = CCSprite::createWithSpriteFrameName(characterImg); // set the position of the block and add it to the layer this->setPosition(CONVERTGRIDTOACTUALPOS_X_Y(gridX,gridY)); this->addChild(_sprite); return true; } Any ideas are welcome at this point!! thanks

    Read the article

  • Remove box2d bodies after collision deduction android?

    - by jubin
    Can any one explain me how to destroy box2d body when collide i have tried but my application crashed.First i have checked al collisions then add all the bodies in array who i want to destroy.I am trying to learning this tutorial My all the bodies are falling i want these bodies should destroy when these bodies will collide my actor monkey but when it collide it destroy but my aplication crashed.I have googled and from google i got the application crash reasons we should not destroy body in step funtion but i am removing body in the last of tick method. could any one help me or provide me code aur check my code why i am getting this prblem or how can i destroy box2d bodies. This is my code what i am doing. Please could any one check my code and tell me what is i am doing wrong for removing bodies. The code is for multiple box2d objects falling on my actor monkey it should be destroy when it will fall on the monkey.It is destroing but my application crahes. static class Box2DLayer extends CCLayer { protected static final float PTM_RATIO = 32.0f; protected static final float WALK_FACTOR = 3.0f; protected static final float MAX_WALK_IMPULSE = 0.2f; protected static final float ANIM_SPEED = 0.3f; int isLeft=0; String dir=""; int x =0; float direction; CCColorLayer objectHint; // protected static final float PTM_RATIO = 32.0f; protected World _world; protected static Body spriteBody; CGSize winSize = CCDirector.sharedDirector().winSize(); private static int count = 200; protected static Body monkey_body; private static Body bodies; CCSprite monkey; float animDelay; int animPhase; CCSpriteSheet danceSheet = CCSpriteSheet.spriteSheet("phases.png"); CCSprite _block; List<Body> toDestroy = new ArrayList<Body>(); //CCSpriteSheet _spriteSheet; private static MyContactListener _contactListener = new MyContactListener(); public Box2DLayer() { this.setIsAccelerometerEnabled(true); CCSprite bg = CCSprite.sprite("jungle.png"); addChild(bg,0); bg.setAnchorPoint(0,0); bg.setPosition(0,0); CGSize s = CCDirector.sharedDirector().winSize(); // Use scaled width and height so that our boundaries always match the current screen float scaledWidth = s.width/PTM_RATIO; float scaledHeight = s.height/PTM_RATIO; Vector2 gravity = new Vector2(0.0f, -30.0f); boolean doSleep = false; _world = new World(gravity, doSleep); // Create edges around the entire screen // Define the ground body. BodyDef bxGroundBodyDef = new BodyDef(); bxGroundBodyDef.position.set(0.0f, 0.0f); // The body is also added to the world. Body groundBody = _world.createBody(bxGroundBodyDef); // Register our contact listener // Define the ground box shape. PolygonShape groundBox = new PolygonShape(); Vector2 bottomLeft = new Vector2(0f,0f); Vector2 topLeft = new Vector2(0f,scaledHeight); Vector2 topRight = new Vector2(scaledWidth,scaledHeight); Vector2 bottomRight = new Vector2(scaledWidth,0f); // bottom groundBox.setAsEdge(bottomLeft, bottomRight); groundBody.createFixture(groundBox,0); // top groundBox.setAsEdge(topLeft, topRight); groundBody.createFixture(groundBox,0); // left groundBox.setAsEdge(topLeft, bottomLeft); groundBody.createFixture(groundBox,0); // right groundBox.setAsEdge(topRight, bottomRight); groundBody.createFixture(groundBox,0); CCSprite floorbg = CCSprite.sprite("grassbehind.png"); addChild(floorbg,1); floorbg.setAnchorPoint(0,0); floorbg.setPosition(0,0); CCSprite floorfront = CCSprite.sprite("grassfront.png"); floorfront.setTag(2); this.addBoxBodyForSprite(floorfront); addChild(floorfront,3); floorfront.setAnchorPoint(0,0); floorfront.setPosition(0,0); addChild(danceSheet); //CCSprite monkey = CCSprite.sprite(danceSheet, CGRect.make(0, 0, 48, 73)); //addChild(danceSprite); monkey = CCSprite.sprite("arms_up.png"); monkey.setTag(2); monkey.setPosition(200,100); BodyDef spriteBodyDef = new BodyDef(); spriteBodyDef.type = BodyType.DynamicBody; spriteBodyDef.bullet=true; spriteBodyDef.position.set(200 / PTM_RATIO, 300 / PTM_RATIO); monkey_body = _world.createBody(spriteBodyDef); monkey_body.setUserData(monkey); PolygonShape spriteShape = new PolygonShape(); spriteShape.setAsBox(monkey.getContentSize().width/PTM_RATIO/2, monkey.getContentSize().height/PTM_RATIO/2); FixtureDef spriteShapeDef = new FixtureDef(); spriteShapeDef.shape = spriteShape; spriteShapeDef.density = 2.0f; spriteShapeDef.friction = 0.70f; spriteShapeDef.restitution = 0.0f; monkey_body.createFixture(spriteShapeDef); //Vector2 force = new Vector2(10, 10); //monkey_body.applyLinearImpulse(force, spriteBodyDef.position); addChild(monkey,10000); this.schedule(tickCallback); this.schedule(createobjects, 2.0f); objectHint = CCColorLayer.node(ccColor4B.ccc4(255,0,0,128), 200f, 100f); addChild(objectHint, 15000); objectHint.setVisible(false); _world.setContactListener(_contactListener); } private UpdateCallback tickCallback = new UpdateCallback() { public void update(float d) { tick(d); } }; private UpdateCallback createobjects = new UpdateCallback() { public void update(float d) { secondUpdate(d); } }; private void secondUpdate(float dt) { this.addNewSprite(); } public void addBoxBodyForSprite(CCSprite sprite) { BodyDef spriteBodyDef = new BodyDef(); spriteBodyDef.type = BodyType.StaticBody; //spriteBodyDef.bullet=true; spriteBodyDef.position.set(sprite.getPosition().x / PTM_RATIO, sprite.getPosition().y / PTM_RATIO); spriteBody = _world.createBody(spriteBodyDef); spriteBody.setUserData(sprite); Vector2 verts[] = { new Vector2(-11.8f / PTM_RATIO, -24.5f / PTM_RATIO), new Vector2(11.7f / PTM_RATIO, -24.0f / PTM_RATIO), new Vector2(29.2f / PTM_RATIO, -14.0f / PTM_RATIO), new Vector2(28.7f / PTM_RATIO, -0.7f / PTM_RATIO), new Vector2(8.0f / PTM_RATIO, 18.2f / PTM_RATIO), new Vector2(-29.0f / PTM_RATIO, 18.7f / PTM_RATIO), new Vector2(-26.3f / PTM_RATIO, -12.2f / PTM_RATIO) }; PolygonShape spriteShape = new PolygonShape(); spriteShape.set(verts); //spriteShape.setAsBox(sprite.getContentSize().width/PTM_RATIO/2, //sprite.getContentSize().height/PTM_RATIO/2); FixtureDef spriteShapeDef = new FixtureDef(); spriteShapeDef.shape = spriteShape; spriteShapeDef.density = 2.0f; spriteShapeDef.friction = 0.70f; spriteShapeDef.restitution = 0.0f; spriteShapeDef.isSensor=true; spriteBody.createFixture(spriteShapeDef); } public void addNewSprite() { count=0; Random rand = new Random(); int Number = rand.nextInt(10); switch(Number) { case 0: _block = CCSprite.sprite("banana.png"); break; case 1: _block = CCSprite.sprite("backpack.png");break; case 2: _block = CCSprite.sprite("statue.png");break; case 3: _block = CCSprite.sprite("pineapple.png");break; case 4: _block = CCSprite.sprite("bananabunch.png");break; case 5: _block = CCSprite.sprite("hat.png");break; case 6: _block = CCSprite.sprite("canteen.png");break; case 7: _block = CCSprite.sprite("banana.png");break; case 8: _block = CCSprite.sprite("statue.png");break; case 9: _block = CCSprite.sprite("hat.png");break; } int padding=20; //_block.setPosition(CGPoint.make(100, 100)); // Determine where to spawn the target along the Y axis CGSize winSize = CCDirector.sharedDirector().displaySize(); int minY = (int)(_block.getContentSize().width / 2.0f); int maxY = (int)(winSize.width - _block.getContentSize().width / 2.0f); int rangeY = maxY - minY; int actualY = rand.nextInt(rangeY) + minY; // Create block and add it to the layer float xOffset = padding+_block.getContentSize().width/2+((_block.getContentSize().width+padding)*count); _block.setPosition(CGPoint.make(actualY, 750)); _block.setTag(1); float w = _block.getContentSize().width; objectHint.setVisible(true); objectHint.changeWidth(w); objectHint.setPosition(actualY-w/2, 460); this.addChild(_block,10000); // Create ball body and shape BodyDef ballBodyDef1 = new BodyDef(); ballBodyDef1.type = BodyType.DynamicBody; ballBodyDef1.position.set(actualY/PTM_RATIO, 480/PTM_RATIO); bodies = _world.createBody(ballBodyDef1); bodies.setUserData(_block); PolygonShape circle1 = new PolygonShape(); Vector2 verts[] = { new Vector2(-11.8f / PTM_RATIO, -24.5f / PTM_RATIO), new Vector2(11.7f / PTM_RATIO, -24.0f / PTM_RATIO), new Vector2(29.2f / PTM_RATIO, -14.0f / PTM_RATIO), new Vector2(28.7f / PTM_RATIO, -0.7f / PTM_RATIO), new Vector2(8.0f / PTM_RATIO, 18.2f / PTM_RATIO), new Vector2(-29.0f / PTM_RATIO, 18.7f / PTM_RATIO), new Vector2(-26.3f / PTM_RATIO, -12.2f / PTM_RATIO) }; circle1.set(verts); FixtureDef ballShapeDef1 = new FixtureDef(); ballShapeDef1.shape = circle1; ballShapeDef1.density = 10.0f; ballShapeDef1.friction = 0.0f; ballShapeDef1.restitution = 0.1f; bodies.createFixture(ballShapeDef1); count++; //Remove(); } @Override public void ccAccelerometerChanged(float accelX, float accelY, float accelZ) { //Apply the directional impulse /*float impulse = monkey_body.getMass()*accelY*WALK_FACTOR; Vector2 force = new Vector2(impulse, 0); monkey_body.applyLinearImpulse(force, monkey_body.getWorldCenter());*/ walk(accelY); //Remove(); } private void walk(float accelY) { // TODO Auto-generated method stub direction = accelY; } private void Remove() { for (Iterator<MyContact> it1 = _contactListener.mContacts.iterator(); it1.hasNext();) { MyContact contact = it1.next(); Body bodyA = contact.fixtureA.getBody(); Body bodyB = contact.fixtureB.getBody(); // See if there's any user data attached to the Box2D body // There should be, since we set it in addBoxBodyForSprite if (bodyA.getUserData() != null && bodyB.getUserData() != null) { CCSprite spriteA = (CCSprite) bodyA.getUserData(); CCSprite spriteB = (CCSprite) bodyB.getUserData(); // Is sprite A a cat and sprite B a car? If so, push the cat // on a list to be destroyed... if (spriteA.getTag() == 1 && spriteB.getTag() == 2) { //Log.v("dsfds", "dsfsd"+bodyA); //_world.destroyBody(bodyA); // removeChild(spriteA, true); toDestroy.add(bodyA); } // Is sprite A a car and sprite B a cat? If so, push the cat // on a list to be destroyed... else if (spriteA.getTag() == 2 && spriteB.getTag() == 1) { //Log.v("dsfds", "dsfsd"+bodyB); toDestroy.add(bodyB); } } } // Loop through all of the box2d bodies we want to destroy... for (Iterator<Body> it1 = toDestroy.iterator(); it1.hasNext();) { Body body = it1.next(); // See if there's any user data attached to the Box2D body // There should be, since we set it in addBoxBodyForSprite if (body.getUserData() != null) { // We know that the user data is a sprite since we set // it that way, so cast it... CCSprite sprite = (CCSprite) body.getUserData(); // Remove the sprite from the scene _world.destroyBody(body); removeChild(sprite, true); } // Destroy the Box2D body as well // _contactListener.mContacts.remove(0); } } public synchronized void tick(float delta) { synchronized (_world) { _world.step(delta, 8, 3); //_world.clearForces(); //addNewSprite(); } CCAnimation danceAnimation = CCAnimation.animation("dance", 1.0f); // Iterate over the bodies in the physics world Iterator<Body> it = _world.getBodies(); while(it.hasNext()) { Body b = it.next(); Object userData = b.getUserData(); if (userData != null && userData instanceof CCSprite) { //Synchronize the Sprites position and rotation with the corresponding body CCSprite sprite = (CCSprite)userData; if(sprite.getTag()==1) { //b.applyLinearImpulse(force, pos); sprite.setPosition(b.getPosition().x * PTM_RATIO, b.getPosition().y * PTM_RATIO); sprite.setRotation(-1.0f * ccMacros.CC_RADIANS_TO_DEGREES(b.getAngle())); } else { //Apply the directional impulse float impulse = monkey_body.getMass()*direction*WALK_FACTOR; Vector2 force = new Vector2(impulse, 0); b.applyLinearImpulse(force, b.getWorldCenter()); sprite.setPosition(b.getPosition().x * PTM_RATIO, b.getPosition().y * PTM_RATIO); animDelay -= 1.0f/60.0f; if(animDelay <= 0) { animDelay = ANIM_SPEED; animPhase++; if(animPhase > 2) { animPhase = 1; } } if(direction < 0 ) { isLeft=1; } else { isLeft=0; } if(isLeft==1) { dir = "left"; } else { dir = "right"; } float standingLimit = (float) 0.1f; float vX = monkey_body.getLinearVelocity().x; if((vX > -standingLimit)&& (vX < standingLimit)) { // Log.v("sasd", "standing"); } else { } } } } Remove(); } } Sorry for my english. Thanks in advance.

    Read the article

< Previous Page | 1 2 3