Search Results

Search found 658 results on 27 pages for 'sprites'.

Page 6/27 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Spritesheet per pixel collision XNA

    - by Jixi
    So basically i'm using this: public bool IntersectPixels(Rectangle rectangleA, Color[] dataA,Rectangle rectangleB, Color[] dataB) { int top = Math.Max(rectangleA.Top, rectangleB.Top); int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom); int left = Math.Max(rectangleA.Left, rectangleB.Left); int right = Math.Min(rectangleA.Right, rectangleB.Right); for (int y = top; y < bottom; y++) { for (int x = left; x < right; x++) { Color colorA = dataA[(x - rectangleA.Left) + (y - rectangleA.Top) * rectangleA.Width]; Color colorB = dataB[(x - rectangleB.Left) + (y - rectangleB.Top) * rectangleB.Width]; if (colorA.A != 0 && colorB.A != 0) { return true; } } } return false; } In order to detect collision, but i'm unable to figure out how to use it with animated sprites. This is my animation update method: public void AnimUpdate(GameTime gameTime) { if (!animPaused) { animTimer += (float)gameTime.ElapsedGameTime.TotalMilliseconds; if (animTimer > animInterval) { currentFrame++; animTimer = 0f; } if (currentFrame > endFrame || endFrame <= currentFrame || currentFrame < startFrame) { currentFrame = startFrame; } objRect = new Rectangle(currentFrame * TextureWidth, frameRow * TextureHeight, TextureWidth, TextureHeight); origin = new Vector2(objRect.Width / 2, objRect.Height / 2); } } Which works with multiple rows and columns. and how i call the intersect: public bool IntersectPixels(Obj me, Vector2 pos, Obj o) { Rectangle collisionRect = new Rectangle(me.objRect.X, me.objRect.Y, me.objRect.Width, me.objRect.Height); collisionRect.X += (int)pos.X; collisionRect.Y += (int)pos.Y; if (IntersectPixels(collisionRect, me.TextureData, o.objRect, o.TextureData)) { return true; } return false; } Now my guess is that i have to update the textureData everytime the frame changes, no? If so then i already tried it and miserably failed doing so :P Any hints, advices? If you need to see any more of my code just let me know and i'll update the question. Updated almost functional collisionRect: collisionRect = new Rectangle((int)me.Position.X, (int)me.Position.Y, me.Texture.Width / (int)((me.frameCount - 1) * me.TextureWidth), me.Texture.Height); What it does now is "move" the block up 50%, shouldn't be too hard to figure out. Update: Alright, so here's a functional collision rectangle(besides the height issue) collisionRect = new Rectangle((int)me.Position.X, (int)me.Position.Y, me.TextureWidth / (int)me.frameCount - 1, me.TextureHeight); Now the problem is that using breakpoints i found out that it's still not getting the correct color values of the animated sprite. So it detects properly but the color values are always: R:0 G:0 B:0 A:0 ??? disregard that, it's not true afterall =P For some reason now the collision area height is only 1 pixel..

    Read the article

  • Detect multitouch (two fingers touch) on a sprite to apply pinch zoom behaviour

    - by Tahreem
    I am using andengine, want to move, zoom and rotate multiple sprites individually on a scene. I have achieved "move" but for pinch zoom i am unable to get the event to two fingers' touch. Below is the code: public class Main extends SimpleBaseGameActivity { private Camera camera; private BitmapTextureAtlas mBitmapTextureAtlas; private ITextureRegion mFaceTextureRegion; private ITextureRegion mFaceTextureRegion2; Sprite face2; private static final int CAMERA_WIDTH = 800; private static final int CAMERA_HEIGHT = 480; @Override public EngineOptions onCreateEngineOptions() { camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy( CAMERA_WIDTH, CAMERA_HEIGHT), camera); return engineOptions; } @Override protected void onCreateResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas( this.getTextureManager(), 1024, 1600, TextureOptions.NEAREST); BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, // this, "ui_ball_1.png", 0, 0, 1, 1), // this.getVertexBufferObjectManager()); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory .createFromAsset(this.mBitmapTextureAtlas, this, "ui_ball_1.png", 0, 0); this.mFaceTextureRegion2 = BitmapTextureAtlasTextureRegionFactory .createFromAsset(this.mBitmapTextureAtlas, this, "ui_ball_1.png", 0, 0); this.mBitmapTextureAtlas.load(); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override protected Scene onCreateScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new Background(0.09804f, 0.6274f, 0.8784f)); final float centerX = (CAMERA_WIDTH - this.mFaceTextureRegion .getWidth()) / 2; final float centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion .getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion, this.getVertexBufferObjectManager()) { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2); return true; } }; face.setScale(2); scene.attachChild(face); scene.registerTouchArea(face); face2 = new Sprite(200, 200, this.mFaceTextureRegion2, this.getVertexBufferObjectManager()) { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { switch(pSceneTouchEvent.getAction()){ case TouchEvent.ACTION_DOWN: int count = pSceneTouchEvent.getMotionEvent().getPointerCount() ; for(int i= 0; i <count; i++) { int id = pSceneTouchEvent.getMotionEvent().getPointerId(i); } break; case TouchEvent.ACTION_MOVE: this.setPosition(pSceneTouchEvent.getX() -this.getWidth() / 2, pSceneTouchEvent.getY()-this.getHeight() / 2); break; case TouchEvent.ACTION_UP: break; } return true; } }; face2.setScale(2); scene.attachChild(face2); scene.registerTouchArea(face2); scene.setTouchAreaBindingOnActionDownEnabled(true); return scene; } } This line int count = pSceneTouchEvent.getMotionEvent().getPointerCount() ; should set 2 to the count variable if i touch the sprite with to fingers, then i can apply zooming functionality (setScale method) on the sprite by getting the distance between the coordinates of two fingers. Can anyone help me? why it does not detect two fingers? and without this how can i zoom the sprite on pinch of two fingers? I am very new to game development, any help would be appreciated. Thanks in advance.

    Read the article

  • Spritebatch drawing sprite with jagged borders

    - by Mutoh
    Alright, I've been on the making of a sprite class and a sprite sheet manager, but have come across this problem. Pretty much, the project is acting like so; for example: Let's take this .png image, with a transparent background. Note how it has alpha-transparent pixels around it in the lineart. Now, in the latter link's image, in the left (with CornflowerBlue background) it is shown the image drawn in another project (let's call it "Project1") with a simpler sprite class - there, it works. The right (with Purple background for differentiating) shows it drawn with a different class in "Project2" - where the problem manifests itself. This is the Sprite class of Project1: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace WindowsGame2 { class Sprite { Vector2 pos = new Vector2(0, 0); Texture2D image; Rectangle size; float scale = 1.0f; // --- public float X { get { return pos.X; } set { pos.X = value; } } public float Y { get { return pos.Y; } set { pos.Y = value; } } public float Width { get { return size.Width; } } public float Height { get { return size.Height; } } public float Scale { get { return scale; } set { if (value < 0) value = 0; scale = value; if (image != null) { size.Width = (int)(image.Width * scale); size.Height = (int)(image.Height * scale); } } } // --- public void Load(ContentManager Man, string filename) { image = Man.Load<Texture2D>(filename); size = new Rectangle( 0, 0, (int)(image.Width * scale), (int)(image.Height * scale) ); } public void Become(Texture2D frame) { image = frame; size = new Rectangle( 0, 0, (int)(image.Width * scale), (int)(image.Height * scale) ); } public void Draw(SpriteBatch Desenhista) { // Desenhista.Draw(image, pos, Color.White); Desenhista.Draw( image, pos, new Rectangle( 0, 0, image.Width, image.Height ), Color.White, 0.0f, Vector2.Zero, scale, SpriteEffects.None, 0 ); } } } And this is the code in Project2, a rewritten, pretty much, version of the previous class. In this one I added sprite sheet managing and, in particular, removed Load and Become, to allow for static resources and only actual Sprites to be instantiated. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace Mobby_s_Adventure { // Actually, I might desconsider this, and instead use static AnimationLocation[] and instanciated ID and Frame; // For determining the starting frame of an animation in a sheet and being able to iterate through // the Rectangles vector of the Sheet; class AnimationLocation { public int Location; public int FrameCount; // --- public AnimationLocation(int StartingRow, int StartingColumn, int SheetWidth, int NumberOfFrames) { Location = (StartingRow * SheetWidth) + StartingColumn; FrameCount = NumberOfFrames; } public AnimationLocation(int PositionInSheet, int NumberOfFrames) { Location = PositionInSheet; FrameCount = NumberOfFrames; } public static int CalculatePosition(int StartingRow, int StartingColumn, SheetManager Sheet) { return ((StartingRow * Sheet.Width) + StartingColumn); } } class Sprite { // The general stuff; protected SheetManager Sheet; protected Vector2 Position; public Vector2 Axis; protected Color _Tint; public float Angle; public float Scale; protected SpriteEffects _Effect; // --- // protected AnimationManager Animation; // For managing the animations; protected AnimationLocation[] Animation; public int AnimationID; protected int Frame; // --- // Properties for easy accessing of the position of the sprite; public float X { get { return Position.X; } set { Position.X = Axis.X + value; } } public float Y { get { return Position.Y; } set { Position.Y = Axis.Y + value; } } // --- // Properties for knowing the size of the sprite's frames public float Width { get { return Sheet.FrameWidth * Scale; } } public float Height { get { return Sheet.FrameHeight * Scale; } } // --- // Properties for more stuff; public Color Tint { set { _Tint = value; } } public SpriteEffects Effect { set { _Effect = value; } } public int FrameID { get { return Frame; } set { if (value >= (Animation[AnimationID].FrameCount)) value = 0; Frame = value; } } // --- // The only things that will be constantly modified will be AnimationID and FrameID, anything else only // occasionally; public Sprite(SheetManager SpriteSheet, AnimationLocation[] Animations, Vector2 Location, Nullable<Vector2> Origin = null) { // Assign the sprite's sprite sheet; // (Passed by reference! To allow STATIC sheets!) Sheet = SpriteSheet; // Define the animations that the sprite has available; // (Passed by reference! To allow STATIC animation boundaries!) Animation = Animations; // Defaulting some numerical values; Angle = 0.0f; Scale = 1.0f; _Tint = Color.White; _Effect = SpriteEffects.None; // If the user wants a default Axis, it is set in the middle of the frame; if (Origin != null) Axis = Origin.Value; else Axis = new Vector2( Sheet.FrameWidth / 2, Sheet.FrameHeight / 2 ); // Now that we have the axis, we can set the position with no worries; X = Location.X; Y = Location.Y; } // Simply put, draw the sprite with all its characteristics; public void Draw(SpriteBatch Drafter) { Drafter.Draw( Sheet.Texture, Position, Sheet.Rectangles[Animation[AnimationID].Location + FrameID], // Find the rectangle which frames the wanted image; _Tint, Angle, Axis, Scale, _Effect, 0.0f ); } } } And, in any case, this is the SheetManager class found in the previous code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace Mobby_s_Adventure { class SheetManager { protected Texture2D SpriteSheet; // For storing the sprite sheet; // Number of rows and frames in each row in the SpriteSheet; protected int NumberOfRows; protected int NumberOfColumns; // Size of a single frame; protected int _FrameWidth; protected int _FrameHeight; public Rectangle[] Rectangles; // For storing each frame; // --- public int Width { get { return NumberOfColumns; } } public int Height { get { return NumberOfRows; } } // --- public int FrameWidth { get { return _FrameWidth; } } public int FrameHeight { get { return _FrameHeight; } } // --- public Texture2D Texture { get { return SpriteSheet; } } // --- public SheetManager (Texture2D Texture, int Rows, int FramesInEachRow) { // Normal assigning SpriteSheet = Texture; NumberOfRows = Rows; NumberOfColumns = FramesInEachRow; _FrameHeight = Texture.Height / NumberOfRows; _FrameWidth = Texture.Width / NumberOfColumns; // Framing everything Rectangles = new Rectangle[NumberOfRows * NumberOfColumns]; int ID = 0; for (int i = 0; i < NumberOfRows; i++) { for (int j = 0; j < NumberOfColumns; j++) { Rectangles[ID] = new Rectangle ( _FrameWidth * j, _FrameHeight * i, _FrameWidth, _FrameHeight ); ID++; } } } public SheetManager (Texture2D Texture, int NumberOfFrames): this(Texture, 1, NumberOfFrames) { } } } For even more comprehending, if needed, here is how the main code looks like (it's just messing with the class' capacities, nothing actually; the result is a disembodied feet walking in place animation on the top-left of the screen and a static axe nearby): using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.Threading; namespace Mobby_s_Adventure { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; static List<Sprite> ToDraw; static Texture2D AxeSheet; static Texture2D FeetSheet; static SheetManager Axe; static Sprite Jojora; static AnimationLocation[] Hack = new AnimationLocation[1]; static SheetManager Feet; static Sprite Mutoh; static AnimationLocation[] FeetAnimations = new AnimationLocation[2]; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; this.TargetElapsedTime = TimeSpan.FromMilliseconds(100); this.IsFixedTimeStep = true; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // Loading logic ToDraw = new List<Sprite>(); AxeSheet = Content.Load<Texture2D>("Sheet"); FeetSheet = Content.Load<Texture2D>("Feet Sheet"); Axe = new SheetManager(AxeSheet, 1); Hack[0] = new AnimationLocation(0, 1); Jojora = new Sprite(Axe, Hack, new Vector2(100, 100), new Vector2(5, 55)); Jojora.AnimationID = 0; Jojora.FrameID = 0; Feet = new SheetManager(FeetSheet, 8); FeetAnimations[0] = new AnimationLocation(1, 7); FeetAnimations[1] = new AnimationLocation(0, 1); Mutoh = new Sprite(Feet, FeetAnimations, new Vector2(0, 0)); Mutoh.AnimationID = 0; Mutoh.FrameID = 0; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // Update logic Mutoh.FrameID++; ToDraw.Add(Mutoh); ToDraw.Add(Jojora); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Purple); // Drawing logic spriteBatch.Begin(); foreach (Sprite Element in ToDraw) { Element.Draw(spriteBatch); } spriteBatch.Draw(Content.Load<Texture2D>("Sheet"), new Rectangle(50, 50, 55, 60), Color.White); spriteBatch.End(); base.Draw(gameTime); } } } Please help me find out what I'm overlooking! One thing that I have noticed and could aid is that, if inserted the equivalent of this code spriteBatch.Draw( Content.Load<Texture2D>("Image Location"), new Rectangle(X, Y, images width, height), Color.White ); in Project2's Draw(GameTime) of the main loop, it works. EDIT Ok, even if the matter remains unsolved, I have made some more progress! As you see, I managed to get the two kinds of rendering in the same project (the aforementioned Project2, with the more complex Sprite class). This was achieved by adding the following code to Draw(GameTime): protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Purple); // Drawing logic spriteBatch.Begin(); foreach (Sprite Element in ToDraw) { Element.Draw(spriteBatch); } // Starting here spriteBatch.Draw( Axe.Texture, new Vector2(65, 100), new Rectangle ( 0, 0, Axe.FrameWidth, Axe.FrameHeight ), Color.White, 0.0f, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0.0f ); // Ending here spriteBatch.End(); base.Draw(gameTime); } (Supposing that Axe is the SheetManager containing the texture, sorry if the "jargons" of my code confuse you :s) Thus, I have noticed that the problem is within the Sprite class. But I only get more clueless, because even after modifying its Draw function to this: public void Draw(SpriteBatch Drafter) { /*Drafter.Draw( Sheet.Texture, Position, Sheet.Rectangles[Animation[AnimationID].Location + FrameID], // Find the rectangle which frames the wanted image; _Tint, Angle, Axis, Scale, _Effect, 0.0f );*/ Drafter.Draw( Sheet.Texture, Position, new Rectangle( 0, 0, Sheet.FrameWidth, Sheet.FrameHeight ), Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0 ); } to make it as simple as the patch of code that works, it still draws the sprite jaggedly!

    Read the article

  • set TouchEvent to every particle in SpriteParticleSystem in andEngine livewallpaper

    - by Girish Bhutiya
    All I have working on andEngine Live wallpaper and I have use SpriteParticleSystem. I want to add touch event to every Sprite of SpriteParticleSystem and remove that sprite from scene. I have use below code for create particle system. final SpriteParticleSystem particleSystem = new SpriteParticleSystem(new PointParticleEmitter(mParticleX, mParticleY),mParticleMinRate, mParticleMaxRate, mParticleMax,this.mFlowerTextureRegion, this.getVertexBufferObjectManager()); //particleSystem.addParticleInitializer(new BlendFunctionParticleInitializer<Sprite>(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE)); particleSystem.addParticleInitializer(new VelocityParticleInitializer<Sprite>(-90, 0, 0, 0)); particleSystem.addParticleInitializer(new AccelerationParticleInitializer<Sprite>(8, -11)); particleSystem.addParticleInitializer(new RotationParticleInitializer<Sprite>(0.0f, 360.0f)); //particleSystem.addParticleInitializer(new ColorParticleInitializer<Sprite>(1.0f, 1.0f, 0.0f)); particleSystem.addParticleInitializer(new ExpireParticleInitializer<Sprite>(15.5f)); particleSystem.addParticleModifier(new ScaleParticleModifier<Sprite>(0, 5, 0.5f, 2.0f)); background = new Sprite(0, 0, backgroundTextureRegion, mEngine.getVertexBufferObjectManager()); background.setPosition((CAMERA_WIDTH - background.getWidth()) * 0.5f, (CAMERA_HEIGHT - background.getHeight()) * 0.5f); //background.setScale(1.5f); //SpriteBackground bg = new SpriteBackground(background); //mScene.setBackground(bg); this.mScene.attachChild(background); this.mScene.attachChild(particleSystem); <br> Thanks in advance.

    Read the article

  • How to move a sprite automatically using a physicsHandler in Andengine?

    - by shailenTJ
    I use a DigitalOnScreenControl (knob with a four-directional arrow control) to move the entity and the entity which is bound to a physicsHandler. physicsHandler.setEntity(sprite); sprite.registerUpdateHandler(physicsHandler); From the DigitalOnScreenControl, I know which direction I want my sprite to move. Inside its overridden onControlChange function, I call a function animateSprite that checks which direction I chose. Based on the direction, I animate my sprite differently. PROBLEM: I want to automatically move the sprite to a specific location on the scene, say at coordinates (207, 305). My sprite is at (100, 305, which means it has to move down by 107 pixels. How do I tell the physicsHandler to move the sprite down by 107 pixels? My animateSprite method will take care of animating the sprite's downward motion. Thank you for your input!

    Read the article

  • libgdx spite position relative to body

    - by While-E
    Apologies if this is a reiteration, as I couldn't find another discussion of this over the past couple days. Issue: I'm using libgdx and box2d, and I'm currently updating the sprite's position to the body's current position every render call. Using a debugRenderer to see the bodies, I see that there is fairly noticeable lag between the movement/position of the body and the sprite that is being moved relative to it. Question: Is this lag normal, possibly to perform collisions ahead of time? If not, should I be manipulating/relating the positions differently? Thanks in advance! [Solution] This was a coding error on my part. Pointed out by a good reply below, I was updating the position of the sprite relative to the body and then stepping the physics. Thus never actually setting the sprite to the body's CURRENT position. Thanks!

    Read the article

  • how to re-use a sprite in cocos2d-x

    - by zinking
    some times it takes time to create the sprite structures in the scene, I might need to setup structures inside this sprite to meet requirement, thus I would hope to reuse such structures with the game again and again. I tried that, remove the child from parent, detach it from parent , clean parent with the sprite. but when I try to add the sprite to another scene, it's just wont pass the assertion that the sprite already have parent did I miss some step ? add an example: I have a sprite A which involves of quite a few steps to construct, so I used it in scene A layer A, and then I want to use it in scene A layer B, scene B layer A1 etc..... generally speaking I don't want to reconstruct the sprte again.

    Read the article

  • XNA 2D Collision with specific tiles

    - by zenzero
    I am new to game programming and to these sites for help. I am making a 2D game but I can't seem to get the collision between my character and certain tiles. I have a map filled with grass tiles and water tiles and I want to keep my character from walking on the water tiles. I have a Tiles class that I use so that the tiles are objects and also has the collision method in it, a TileEngine class used create the map and it also holds a list of Tiles, and the class James which is for my character. I also have a Camera class that centers the camera on my character if that has anything to do with the problem. The character's movement is intended to be restricted to 4 directions(up, down, left, right). As an extra note, the bottom right water tile does have collision, but the collision does not occur for any of the other water tiles. Here is my TileEngine class using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Test2DGame2 { class TileEngine : Microsoft.Xna.Framework.Game { //makes a list of Tiles objects public List<Tiles> tilesList = new List<Tiles>(); public TileEngine() {} public static int tileWidth = 64; public static int tileHeight = 64; public int[,] map = { {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,}, }; public void drawMap(SpriteBatch spriteBatch) { for (int y = 0; y < map.GetLength(0); y++) { for (int x = 0; x < map.GetLength(1); x++) { //make a Rectangle tilesList[map[y, x]].rectangle = new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight); //draw the Tiles objects spriteBatch.Draw(tilesList[map[y, x]].texture, tilesList[map[y, x]].rectangle, Color.White); } } } } } Here is my Tiles class using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Test2DGame2 { class Tiles { public Texture2D texture; public Rectangle rectangle; public Tiles(Texture2D texture) { this.texture = texture; } //check to see if james collides with the tile from the right side public void rightCollision(James james) { if (james.GetBounds().Intersects(rectangle)) { james.position.X = rectangle.Left - james.front.Width; } } } } I have a method for rightCollision because I could only figure out how to get the collisions from specifying directions. and here is the James class for my character using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Test2DGame2 { class James { public Texture2D front; public Texture2D back; public Texture2D left; public Texture2D right; public Vector2 center; public Vector2 position; public James(Texture2D front) { position = new Vector2(0, 0); this.front = front; center = new Vector2(front.Width / 2, front.Height / 2); } public James(Texture2D front, Vector2 newPosition) { this.front = front; position = newPosition; center = new Vector2(front.Width / 2, front.Height / 2); } public void move(GameTime gameTime) { KeyboardState keyboard = Keyboard.GetState(); float SCALE = 20.0f; float speed = gameTime.ElapsedGameTime.Milliseconds / 100.0f; if (keyboard.IsKeyDown(Keys.Up)) { position.Y -=speed * SCALE; } else if (keyboard.IsKeyDown(Keys.Down)) { position.Y += speed * SCALE; } else if (keyboard.IsKeyDown(Keys.Left)) { position.X -= speed * SCALE; } else if (keyboard.IsKeyDown(Keys.Right)) { position.X += speed * SCALE; } } public void draw(SpriteBatch spriteBatch) { spriteBatch.Draw(front, position, null, Color.White, 0, center, 1.0f, SpriteEffects.None, 0.0f); } //get the boundingbox for James public Rectangle GetBounds() { return new Rectangle( (int)position.X, (int)position.Y, front.Width, front.Height); } } }

    Read the article

  • Creating Transparent Game Menu Items using AndEngine

    - by Chaitanya Chandurkar
    I'm trying to create a Game Menu which contains some Menu Items like New Game Multiplayer Options Exit I want to make this Menu Items Transparent. Only Text in White color should be visible. So i guess i do not need any background image for Menu Items. I have seen examples of SpriteButton like given below. ButtonSprite playButton = new ButtonSprite(0, 0, btnNormalTextureRegion, btnPushedTextureRegion, this.getVertexBufferObjectManager(), new OnClickListener() { @Override public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) { // Do Stuff here } } The thing which i don't understand is how can i initialize btnNormalTextureRegion? I use the code give below to initialize ITexture and ITextureRegion for objects. mBackgruondTexture = new BitmapTexture(activity.getTextureManager(), new IInputStreamOpener() { public InputStream open() throws IOException { return activity.getAssets().open("gfx/backgrounds/greenbg.jpg"); } }); mBackgruondTextureRegion = TextureRegionFactory.extractFromTexture(mBackgruondTexture); This code openes up an Image from assest. As i do not want to use any image for Menu Item How can i initialize btnNormalTextureRegion for SpriteButton. OR Is there any alternative to create Game Menu?

    Read the article

  • Libgdx detect when player is outside of screen

    - by Rockyy
    Im trying to learn libGDX (coming from XNA/MonoDevelop), and I'm making a super simple test game to get to know it better. I was wondering how to detect if the player sprite is outside of the screen and make it so it is impossible to go outside of the screen edges. In XNA you could do something like this: // Prevent player from moving off the left edge of the screen if (player.Position.X < 0) player.Position = new Vector2(0, player.Position.Y); How is this achieved in libgdx? I think it's the Stage that handles the 2D viewport in libgdx? This is my code so far: private Texture texture; private SpriteBatch batch; private Sprite sprite; @Override public void create () { float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); batch = new SpriteBatch(); texture = new Texture(Gdx.files.internal("player.png")); sprite = new Sprite(texture); sprite.setPosition(w/2 -sprite.getWidth()/2, h/2 - sprite.getHeight()/2); } @Override public void render () { Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){ if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT)) sprite.translateX(-1f); else sprite.translateX(-10.0f); } if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){ if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT)) sprite.translateX(1f); else sprite.translateX(10f); } batch.begin(); sprite.draw(batch); batch.end(); }

    Read the article

  • Exporting the frames in a Flash CS5.5 animation and possibly creating the spritesheet

    - by Adam Smith
    Some time ago, I asked a question here to know what would be the best way to create animations when making an Android game and I got great answers. I did what people told me there by exporting each frame from a Flash animation manually and creating the spritesheet also manually and it was very tedious. Now, I changed project and this one is going to contain a lot more animations and I feel like there has to be a better way to to export each frame individually and possibly create my spritesheets in an automated manner. My designer is using Flash CS5.5 and I was wondering if all of this was possible, as I can't find an option or code examples on how to save each frame individually. If this is not possible using Flash, please recommend me another program that can be used to create animations without having to create each frame on its own. I'd rather keep Flash as my designer knows how to use it and it's giving great results.

    Read the article

  • How to Export Flash Animation Data

    - by charliep
    I'd love for my partner, the artist, to be able to animate using flash movieclips and timelines. Then I, the programmer, would like to read the raw Flash info and re-program it into my engine of choice (which happens to be Torque2D). The data I'd want is the bitmap images that were used in Flash, like the head and body the links between the images, like where the head connects to the body the motion data from the flash animation, like move, rotate (at what speed), shear, etc. for the head or arms or whatever. Is there any way to get this data? Here's what I know so far. There are tools like SWFSheet and Spriteloq that convert the entire flash animation into a frame by frame sprite animation (in a sprite sheet). This would take too much space in my case, so I'd like to avoid that. Re-animating on the fly would take much less texture memory. There is a PDF that describes the SWF file format but NOT the individual components like the movieclips. So anyone know of a library I can use, or how I can learn more about the movieclip components and whatnot? (more better tags: transform, export, convert)

    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

  • how to double buffer in multiple classes with java

    - by kdavis8
    I am creating a Java 2D video game. I can load graphics just fine, but when it gets into double buffering I have issues. My source code package myPackage; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; public class GameView extends JFrame { private BufferedImage backbuffer; private Graphics2D g2d; public GameView() { setBounds(0, 0, 500, 500); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); backbuffer = new BufferedImage(getHeight(), getWidth(), BufferedImage.TYPE_INT_BGR); g2d = backbuffer.createGraphics(); Toolkit tk = Toolkit.getDefaultToolkit(); Image img = tk.getImage(this.getClass().getResource("cage.png")); g2d.setColor(Color.red); //g2d.drawString("Hello",100,100); g2d.drawImage(img, 100, 100, this); repaint(); } public static void main(String args[]) { new GameView(); } public void paint(Graphics g) { g2d = (Graphics2D)g; g2d.drawImage(backbuffer, 0, 0, this); } }

    Read the article

  • Simultaneous Animation for a GameObject - Unity3D

    - by Fahim Ali Zain
    Its my second week with Unity. I am doing a 2D game and I have a small GameObject which should change its sprite along with following a definite path defined in Animation Curves. I did both of them in separate .anim files since the transform animation had many keyframes, i thought it wont be good to put the '2' sprite keyframe repeatedly along side the transform keyframe. But the problem is, I cant get it both working together at the same time. I dont want any blending because the animation is timed well already. Also, I tried deleting the sprite change animation and tried it under script changing the SpriteRenderer.Sprite property under Update(); but it works only when the Animator component is disabled in the GameObject. Any Solutions ? :)

    Read the article

  • Algorithm to reduce a bitmap mask to a list of rectangles?

    - by mos
    Before I go spend an afternoon writing this myself, I thought I'd ask if there was an implementation already available --even just as a reference. The first image is an example of a bitmap mask that I would like to turn into a list of rectangles. A bad algorithm would return every set pixel as a 1x1 rectangle. A good algorithm would look like the second image, where it returns the coordinates of the orange and red rectangles. The fact that the rectangles overlap don't matter, just that there are only two returned. To summarize, the ideal result would be these two rectangles (x, y, w, h): [ { 3, 1, 2, 6 }, { 1, 3, 6, 2 } ]

    Read the article

  • Modern techniques for spriting

    - by DevilWithin
    Hello, I would like to know the flow for making modern 2D game artwork. How are the assets made nowadays? Bitmap? Vector-based? Hand-drawn and painted? Drawn digitally? Modeled in 3D and exported to bitmaps? I would like some information on programs as well, for fine looking art. Why does Flash's vector art style look good in most games? How do I make equivalent graphics with external tools? Or equaly good and not vector-based, anyway. Any special hints for animating? An answer oriented towards a one-man-army indie developer with little experience but some artistic sense would be appreciated! Not a complete dummy with paint programs, but also not a master at all, just need efficient ways to achieve results. Thanks. NOTE: Pixel art is not the goal of this question, nothing related to direct pixel manipulation should be brought up here, but you're free to do exactly that :)

    Read the article

  • How to get quality sprite sheet generation with rotations

    - by BenMaddox
    I'm working on a game that uses sprite sheets with rotation for animations. While the effect is pretty good, the quality of the rotations is somewhat lacking. I exported a flash animation to png sequence and then used a C# app to do matrix based rotations (System.Drawing.Drawing2D.Matrix). Unfortunately, there are several places where the image gets clipped. What would you suggest for a way to get high quality rotations from either flash or the exported PNGs? A circle should fit within the same image boundaries. I don't mind a new program that I must write or an existing program I must download/buy.

    Read the article

  • How to I get a rotated sprite to move left or right?

    - by rphello101
    Using Java/Slick 2D, I'm using the mouse to rotate a sprite on the screen and the directional keys (in this case, WASD) to move the spite. Forwards and backwards is easy, just position += cos(ang)*speed or position -= cos(ang)*speed. But how do I get the sprite to move left or right? I'm thinking it has something to do with adding 90 degrees to the angle or something. Any ideas? Rotation code: int mX = Mouse.getX(); int mY = HEIGHT - Mouse.getY(); int pX = sprite.x+sprite.image.getWidth()/2; int pY = sprite.y+sprite.image.getHeight()/2; double mAng; if(mX!=pX){ mAng = Math.toDegrees(Math.atan2(mY - pY, mX - pX)); if(mAng==0 && mX<=pX) mAng=180; } else{ if(mY>pY) mAng=90; else mAng=270; } sprite.angle = mAng; sprite.image.setRotation((float) mAng); And the movement code (delta is change in time): Input input = gc.getInput(); Vector2f direction = new Vector2f(); Vector2f velocity = new Vector2f(); direction.x = (float) Math.cos(Math.toRadians(sprite.angle)); direction.y = (float) Math.sin(Math.toRadians(sprite.angle)); if(direction.length()>0) direction = direction.normalise(); //On a separate note, what does this line of code do? velocity.x = (float) (direction.x * sprite.moveSpeed); velocity.y = (float) (direction.y * sprite.moveSpeed); if(input.isKeyDown(sprite.up)){ sprite.x += velocity.x*delta; sprite.y += velocity.y*delta; }if (input.isKeyDown(sprite.down)){ sprite.x -= velocity.x*delta; sprite.y -= velocity.y*delta; }if (input.isKeyDown(sprite.left)){ //??? }if (input.isKeyDown(sprite.right)){ //??? }

    Read the article

  • Hero/Character sprite size in comparison to tile size?

    - by Kid
    So I'm making this simple platformer where the Hero is 16x16 in size, but also, the tile size is 16x16. Which sounds fine right? But my game window/world is 800x416, which makes the Hero is really really tiny in comparison. This really surprised me, but given Ive never made a platformer before it is also a new discovery. Is there a rule set for scale in platformer games? I'd like to have my game window remain the size it is (800x416), cause the game involves large levels. But how big should my hero be? I hope I was clear with the question, and I appreciate any insight. Thanks

    Read the article

  • Sprite not rotating around its centre after Scaling at its centre

    - by asma.farhat
    If I scale a sprite at its centre, then try to rotate it around its centre as well, the rotation does not occur around its centre. If you need to rotate, for example a scaled ball,the way its working it is set the scale center at the top left (0,0) set the scale that you want, and then set the rotation center to the middle of the scaled sprite, and then apply the rotation modifier. blaBloBliSprite.setScaleCenter(0, 0); blaBloBliSprite.setScale(0.667f); blaBloBliSprite.setPosition(557, CAMERA_HEIGHT / 2 - blaBloBliSprite.getHeightScaled() / 2); blaBloBliSprite.setRotationCenter(blaBloBliSprite.getWidthScaled() / 2, blaBloBliSprite.getHeightScaled() / 2); But I want to scale a sprite at its centre as well. Is there any way of doing it?

    Read the article

  • Turning on collision crashes game

    - by MomentumGaming
    I am getting a null pointer excecption to both my sprite and level. I am working on my mob class, and when I try to move him and the move function is called, the game crashes after checking collision with a null pointer excecption. Taking out the one line that actually checks if the tile located in front of it fixes the problem. Also, if i keep collision ON but don't move the position of the mob (the spider) the game works fine. I will have collision, and the spider appears on the screen, only problem is, getting it to move causes this nasty error that i just can't fix. true Exception in thread "Display" java.lang.NullPointerException at com.apcompsci.game.entity.mob.Mob.collision(Mob.java:67) at com.apcompsci.game.entity.mob.Mob.move(Mob.java:38) at com.apcompsci.game.entity.mob.spider.update(spider.java:58) at com.apcompsci.game.level.Level.update(Level.java:55) at com.apcompsci.game.Game.update(Game.java:128) at com.apcompsci.game.Game.run(Game.java:106) at java.lang.Thread.run(Unknown Source) Here is my renderMob mehtod: public void renderMob(int xp,int yp,Sprite sprite,int flip) { xp -= xOffset; yp-=yOffset; for(int y = 0; y<32; y++) { int ya = y + yp; int ys = y; if(flip == 2||flip == 3)ys = 31-y; for(int x = 0; x<32; x++) { int xa = x + xp; int xs = x; if(flip == 1||flip == 3)xs = 31-x; if(xa < -32 || xa >=width || ya<0||ya>=height) break; if(xa<0) xa =0; int col = sprite.pixels[xs+ys*32]; if(col!= 0x000000) pixels[xa+ya*width] = col; } } } My spider class which determines the sprite and where I control movement, also rendering the spider onto the screen, when I increment ya to move the sprite, I get the crash, but without ya++, it runs flawlessly with a spider sprite on screen: package com.apcompsci.game.entity.mob; import com.apcompsci.game.entity.mob.Mob.Direction; import com.apcompsci.game.graphics.Screen; import com.apcompsci.game.graphics.Sprite; import com.apcompsci.game.level.Level; public class spider extends Mob{ Direction dir; private Sprite sprite; private boolean walking; public spider(int x, int y) { this.x = x <<4; this.y = y <<4; sprite = sprite.spider_forward; } public void update() { int xa = 0, ya = 0; ya++; if(ya<0) { sprite = sprite.spider_forward; dir = Direction.UP; } if(ya>0) { sprite = sprite.spider_back; dir = Direction.DOWN; } if(xa<0) { sprite = sprite.spider_side; dir = Direction.LEFT; } if(xa>0) { sprite = sprite.spider_side; dir = Direction.LEFT; } if(xa!= 0 || ya!= 0) { System.out.println("true"); move(xa,ya); walking = true; } else{ walking = false; } } public void render(Screen screen) { screen.renderMob(x, y, sprite, 0); } } This is th mob class that contains the move() method that is called in the spider class above. This move method calls the collision method. tile and sprite comes up null in the debugger: package com.apcompsci.game.entity.mob; import java.util.ArrayList; import java.util.List; import com.apcompsci.game.entity.Entity; import com.apcompsci.game.entity.projectile.DemiGodProjectile; import com.apcompsci.game.entity.projectile.Projectile; import com.apcompsci.game.graphics.Sprite; public class Mob extends Entity{ protected Sprite sprite; protected boolean moving = false; protected enum Direction { UP,DOWN,LEFT,RIGHT } protected Direction dir; public void move(int xa,int ya) { if(xa != 0 && ya != 0) { move(xa,0); move(0,ya); return; } if(xa>0) dir = Direction.RIGHT; if(xa<0) dir = Direction.LEFT; if(ya>0)dir = Direction.DOWN; if(ya<0)dir = Direction.UP; if(!collision(xa,ya)){ x+= xa; y+=ya; } } public void update() { } public void shoot(int x, int y, double dir) { //dir = Math.toDegrees(dir); Projectile p = new DemiGodProjectile(x, y,dir); level.addProjectile(p); } public boolean collision(int xa,int ya) { boolean solid = false; for(int c = 0; c<4; c++) { int xt = ((x+xa) + c % 2 * 14 - 8 )/16; int yt = ((y+ya) + c / 2 * 12 +3 )/16; if(level.getTile(xt, yt).solid()) solid = true; } return solid; } public void render() { } } Finally, here is the method in which i call the add() method for the spider to add it to the level: protected void loadLevel(String path) { try{ BufferedImage image = ImageIO.read(SpawnLevel.class.getResource(path)); int w = width =image.getWidth(); int h = height = image.getHeight(); tiles = new int[w*h]; image.getRGB(0, 0, w,h, tiles,0, w); } catch(IOException e){ e.printStackTrace(); System.out.println("Exception! Could not load level file!"); } add(new spider(20,45)); } I don't think i need to include the level class but just in case, I have provided a gistHub link for better context. It contains all of the full classes listed above , plus my entity class and maybe another. Thanks for the help if you decide to do so, much appreciated! Also, please tell me if i'm in the wrong section of stackeoverflow, i figured that since this is the gamign section that it belonged but debugging code normally goes into the general section.

    Read the article

  • Tool for creating Spritesheet? and Tips

    - by Spooks
    I am looking for a tool that I can use to create sprite sheet easily. Right now I am using Illustrator, but I can never get the center of the character in the exact position, so it looks like it is moving around(even though its always in one place), while being loop through the sprite sheet. Is there any better tools that I can be using? Also what kind of tips would you give for working with a sprite sheet? Should I create each part of the character in individual layers (left arm, right arm, body, etc.) or everything at once? any other tips would also be helpful! thank you

    Read the article

  • Why does my sprite glitch when moving? [closed]

    - by rphello101
    Using Slick 2D/Java, I'm using the mouse to rotate a sprite and WASD to move it (A and D are used to strafe). I finally got the directional keys and rotation to work in sync, but I'm having problems with sporadic movement. It seems that the move speed is not always set to the value I have it at. Sometimes the sprite with just shoot across the screen. Furthermore, it seems that at 0 degrees, when the left key is pressed, the sprite moves backwards, not to the left. There also seems to be quite a bit of glitching when two keys are pressed, like left and up. Anyone see anything obvious? Here is the rotational code: int mX = Mouse.getX(); int mY = HEIGHT - Mouse.getY(); int pX = sprite.x+sprite.image.getWidth()/2; int pY = sprite.y+sprite.image.getHeight()/2; double mAng; if(mX!=pX){ mAng = Math.toDegrees(Math.atan2(mY - pY, mX - pX)); if(mAng==0 && mX<=pX) mAng=180; } else{ if(mY>pY) mAng=90; else mAng=270; } sprite.angle = mAng; sprite.image.setRotation((float) mAng); Movement code: Input input = gc.getInput(); Vector2f direction = new Vector2f(); Vector2f velocity = new Vector2f(); Vector2f left; Vector2f right; direction.x = (float) Math.cos(Math.toRadians(sprite.angle)); direction.y = (float) Math.sin(Math.toRadians(sprite.angle)); if(direction.length()>0) direction = direction.normalise(); left = new Vector2f(-direction.y, direction.x); right = new Vector2f(direction.y, -direction.x); velocity.x = (float) (direction.x * sprite.moveSpeed); velocity.y = (float) (direction.y * sprite.moveSpeed); if(input.isKeyDown(sprite.up)){ sprite.x += velocity.x*delta; sprite.y += velocity.y*delta; }if (input.isKeyDown(sprite.down)){ sprite.x -= velocity.x*delta; sprite.y -= velocity.y*delta; }if (input.isKeyDown(sprite.left)){ sprite.x += left.x * sprite.moveSpeed * delta; sprite.y += left.y * sprite.moveSpeed * delta; }if (input.isKeyDown(sprite.right)){ sprite.x += right.x * sprite.moveSpeed * delta; sprite.y += right.y * sprite.moveSpeed * delta; }

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >