_id
int64
0
49
text
stringlengths
71
4.19k
9
Moving a sprite accelerometer Im trying to, in cocos2d for the iPhone, move a CCSprite (in this case "player" up and down (the app is in landscape). How can I accomplish this? I have been unable to do so. ex. (void)accelerometer (UIAccelerometer )accelerometer didAccelerate (UIAcceleration )acceleration player.position.x acceleration.x 10 NSLog( "Accelerometer x value is f n", acceleration.x)
9
OOP in cocos2d for ios I have been pulling my hair out trying to make an object in cocos 2d that is a CCSprite (with an image) and a CCLabelBMFont. I tried making a CCNode object and I tried making a custom CCSprite object but none of it worked! Can someone show me how to do this? Thanks.
9
How to get all child with same tag from CCLayer? Actually i am working with cocos2d Game. I am using CCLayer for particular scene. now there are so many buttons means CCMenuitems are available. I want to disable that all menuitems having same tags.
9
What is the correct way of changing image of existing CCSprite? How do I correctly change sprite to show another image? Or to have another texture? This is the way I do it now. When I need to change sprite image I increase state variable. So i have one picture for 0, another for 1 and another for 2. First i tried just saying mysprite CCSpriteWithFile "sprite.png" but that didn't end up too well since I was making new objects every frame and it got messy pretty fast. So I added a check. There is another variable that is stateChanged and it starts at zero. So I compare state to stateChanged before actually making any sprites and if it differs I do the magic. But here comes the problem. Somehow this sprite won't flip. And I believe the problem is in this method. (void) updateState if (stateChanged ! state) if (state 0) currentSprite CCSprite spriteWithFile "eggclosed.png" self addChild currentSprite if (state 1) currentSprite nil self removeAllChildrenWithCleanup YES currentSprite CCSprite spriteWithFile "eggopen.png" self addChild currentSprite if (state 2) currentSprite nil self removeAllChildrenWithCleanup YES currentSprite CCSprite spriteWithFile "yoshi.png" self addChild currentSprite stateChanged state TLDR How to correctly change image of sprite. I have a Pet object that has a CCSprite property. And I sometimes need to change sprte to look another way. How do?
9
Alternatives to NSMutableArray for storing 2D grid iOS Cocos2d I'm creating a grid based iOS game using Cocos2d. Currently the grid is stored in an NSMutableArray that contains other NSMutableArrays (the latter are rows in the grid). This works ok and performance so far is pretty good. However the syntax feels bulky and the indexing isn't very elegant (using CGPoints, would prefer integer indices). I'm looking for an alternative. What are some alternatives data structures for 2D arrays in this situation? In my game it's very common to add and remove rows from the bottom of the grid. So the grid might start off 10x10, grow to 17x10, shrink to 8x10 and then finally end with 2x10. Note the column count is constant. I've consider using a vector lt vector lt Object gt gt . Also I'm vaguely aware of some type of "fast array" or similar offered by Cocos2d. I'd just like to learn about best practices from other developers!
9
Top down water view, cocos2d Has anyone successfully created a top down view of a stream river? I need to also work out how to make it look like a boat is cutting through the water.
9
Cocos 2D asteroids style movement (iOS) So I have a CCSprite subclass, well call this Spaceship. Spaceship needs to move on a loop, until I say othersise by calling a method. The method should look something like (void)moveForeverAtVelocity method logic The class Spaceship has two relevant iVars, resetPosition and targetPosition, the target is where we are headed, the reset is where we set to when we've hit our target. If they are both off screen this creates a permanent looping effect. So for the logic, I have tried several things, such as CCMoveTo move CCMoveTo actionWithDuration 2 position ccp(100, 100) CCCallBlockN repeat CCCallBlockN actionWithBlock (CCNode node) self moveForeverAtVelocity self runAction CCSequence actions move, repeat, nil self.position self.resetPosition recursively calling the moveForeverAtVelocity method. This is psuedo code, so its not perfect. I have hard coded some of the values for the sake of simplicity. Enough garble The problem I am having, how can I make a method that loops forever, but can be called and reset at will. I'm running into issues with creating multiple instances of this method. If you can offer any assistance with creating this effect, that would be appreciated.
9
Presenting game center leaderboard I have the following code (void)showLeaderboard GKLeaderboardViewController leaderboardController GKLeaderboardViewController alloc init if (leaderboardController ! NULL) leaderboardController.timeScope GKLeaderboardTimeScopeAllTime leaderboardController.leaderboardDelegate self self presentModalViewController leaderboardController animated YES leaderboardController release Which I am trying to use to make my leader board pop up. The issue is cocos2d will not allow me to use the line self presentModalViewController leaderboardController animated YES How do I fix this? Thanks PS I am using cocos2d
9
Projectile immediately intersecting with target I have a fairly simple and somewhat cookie cutter method for testCollisions (FYI BasicProjectile is a CCNode with a CCSprite member). for (BasicProjectile basicProjectile in self.projectiles) NSLog( "projectile sprite ",NSStringFromCGRect(basicProjectile.sprite.boundingBox)) NSLog( "destination sprite ",NSStringFromCGRect(basicProjectile.destination.sprite.boundingBox)) if (CGRectIntersectsRect(basicProjectile.sprite.boundingBox, basicProjectile.destination.sprite.boundingBox)) basicProjectile.destination setHealth (basicProjectile.destination.hp basicProjectile.damage) self.projectiles removeObject basicProjectile self removeChild basicProjectile cleanup YES Those NSLog statements output 2013 03 23 10 02 59.124 GridWars 25268 c07 projectile sprite 10, 10 , 20, 20 2013 03 23 10 02 59.124 GridWars 25268 c07 destination sprite 13.5, 34 , 27, 68 The main problem is that the collision immediately happens. It should take a few frames to travel from the source to the destination. So although the logic of setting the health works fine the sprite itself is never seen on the screen because the very second its fired it is removed. From what I understand about CGRectIntersectsRect those 2 points listed above do not intersect. Am I wrong are they intersecting? What can be causing these projectiles to immediately intersect with their target? BasicProjectile class (CCNODE superclass) (id)initWithSourceAndDestination (GameCharacters )Source destination (GameCharacters )Destination if (self super init ) self.damage 25 self.sprite CCSprite spriteWithFile "Projectile.png" self addChild self.sprite z 1000 self.source Source self.destination Destination return self GameCharacters would look similar to this except have health and mana properties. WizardHero Class, Method Fire basicProjectile.position self.position self.hostLayer addChild basicProjectile z 2021 Determine where we wish to shoot the projectile to int realX Are we shooting to the left or right? CGPoint diff ccpSub(basicProjectile.destination.position, basicProjectile.source.position) if (diff.x gt 0) realX (self.hostLayer.tileMap.mapSize.width self.hostLayer.tileMap.tileSize.width) (basicProjectile.contentSize.width 2) else realX (self.hostLayer.tileMap.mapSize.width self.hostLayer.tileMap.tileSize.width) (basicProjectile.contentSize.width 2) float ratio (float) diff.y (float) diff.x int realY ((realX basicProjectile.position.x) ratio) basicProjectile.position.y CGPoint realDest ccp(realX, realY) Determine the length of how far we're shooting int offRealX realX basicProjectile.position.x int offRealY realY basicProjectile.position.y float length sqrtf((offRealX offRealX) (offRealY offRealY)) float velocity 380 1 380pixels 1sec float realMoveDuration length velocity Move projectile to actual endpoint id actionMoveDone CCCallFuncN actionWithTarget self.hostLayer selector selector(projectileMoveFinished ) basicProjectile runAction CCSequence actionOne CCMoveTo actionWithDuration realMoveDuration position realDest two actionMoveDone self.hostLayer.projectiles addObject basicProjectile Basically here is the class structure Three main superclasses GameProjectiles CCNodes GameLevels CCNodes GameChars CCNodes Then the actual more specific classes (used on the GameLevels) BasicProjectile GameProjectiles Level1Layer GameLevels WizardHero GameCharacters RedEnemy GameCharacters
9
How to use generic level editors with my arbitary code? I have a game, breakout clone. It has a Block class that contains CCSprite as a property. Usually I made levels by manually setting those blocks to positions. Here comes the question, how do I use generic level editors with my custom code? All editors work with CCSprites and not my class. How can I overcome that?
9
Keeping the CCSprite on the screen In my cocos2d app I have a CCSprite moving on the screen but it moves off the screen. How can I prevent the CCSprite from moving off the screen? Thanks
9
How to create fun and interactive menus with cocos2d? Possible Duplicate How to make animated buttons in a menu with Cocos2d? How do I make fun and interactive menus with cocos2d, all the tutorials are just for simple clickable menus. Can any one help me learn this? It would be see the menu flip or slide away, I know you can do this with scenes but how do I make this with just the menu? Let's say the menu is a bunch of cards and I want them to flip over like the sub menu is on the backside of the card, how would I do this? Or, make the Main menu slide in from the left, right, top or bottom side and then when a button is selected it slides away the same way and switch to a sub menu (settings, Score etc)? Anyone? David
9
cocos2dx RunningScene ! Scene You just Replace I have this code for cocos2d x 3.x void MainMenu StartGame(cocos2d Ref pSender) auto director Director getInstance() auto newScene Scene create() director gt replaceScene(newScene) run Scene maybeNewScene director gt getRunningScene() CCASSERT ( maybeNewScene newScene , "...") Assert Fail auto hudLayer HUD create() hudLayer gt setPosition(Vec2 ZERO) scene gt addChild(hudLayer, Z NORMAL) But When I get runnign scene by director gt getRunningScene(), It gives me the scene which was running before calling director gt replaceScene(). (the scene which is going to be destructed soon) When I checked replaceScene() function, This function places newScene in some varibale called nextScene but not assigned it to runningScene . Question How can I access newScene, just some lines further? ( for example in HUD init())
9
Timing use individual timer for every task or global timer? I'm writing a game, where a player controls a spaceship. It regenerates energy over time. So I need to make a little timer that adds certain amount of energy to the pool per second. My enemies also shoot at me, activate different abilities. I figured I can use separate timers for these too. But I see how this can quickly go out of hand, since I have different engines with different energy regeneration rates will I need to replace the timer every time? Or if I have different energy I have to manually track all the timers and set them anew. I thought, maybe I can use some global singleton method that can handle all the timing in my game? It can update everything in the game, and when something new happens (like new enemy spawning) I can just send my singleton information about that object and it will handle all the timing for it? Is this a good approach? Can I read up something about this somewhere? Maybe you have some experience with this?
9
CCParticleSystemQuad works as intended every second time I'm using CCParticleSystemQuad for particles, loading it from plist flourEmitter CCParticleSystemQuad particleWithFile "FlourParticles.plist" But it works not every time. Every second or third time I start a game, particles look different from what I've set them up and there are errors saying it couldn't load image. cocos2d CCTexture2D. Can't create Texture. cgImage is nil cocos2d Couldn't create texture for file in CCTextureCache Of course the image is there and the next time i launch game it works as intended. I cannot think of any ways how to debug this error.
9
Creating multiple fixtures in one body I want to create this type of fixture in one body. Here square and circle both are different fixtures but attach to one body. How do I do this?
9
Presenting game center leaderboard I have the following code (void)showLeaderboard GKLeaderboardViewController leaderboardController GKLeaderboardViewController alloc init if (leaderboardController ! NULL) leaderboardController.timeScope GKLeaderboardTimeScopeAllTime leaderboardController.leaderboardDelegate self self presentModalViewController leaderboardController animated YES leaderboardController release Which I am trying to use to make my leader board pop up. The issue is cocos2d will not allow me to use the line self presentModalViewController leaderboardController animated YES How do I fix this? Thanks PS I am using cocos2d
9
Can I use a shader with 2 different textures in Cocos2D (x)? We are evaluating a variety of different graphic engines for use in our game and we want to be able to use 2 different textures for many of our sprite maps. One sprite map would be the standard RGBA values and the other sprite map would contain normal data for these sprites. To be clear, these are not 3D models. The normal map would just help the flat 2D sprites better react to lighting. I've done this exact thing in OpenGL ES 2.0 and I imagine the shader code would work in Cocos2D, but I'm wondering how I go about doing this in Cocos2D? I know you can assign shaders to sprites, but how would I specify a secondary texture?
9
How do I simulate a swinging pendulum? I want to simulate a rope with a weight attached, swinging back and forth like a pendulum. Any actual physics is overkill it's just endlessly repeating the same motion. JQuery has a the "swing" ease similar to what I'm looking for. How does it work? I was thinking of rotating from one angle to another with Math.easeOutExpo, but real pendulums ease differently...
9
How can I cause the latest touch event to interrupt a prior event in Cocos2D? In Cocos2D for iPhone, I want the latest touch event to interrupt another and ignore the last touch. Let me know if I need to elaborate more, but basically my game consists of a lot of finger dragging, and if the player ever switched fingers, there may be some overlap, and for the way things are setup, it may detect it as a new touch. I think I have things almost on the right track, but my third touch does not work correctly. For instance Touch A begins and held Touch B begins and held Touch A let go Touch A begins and held lt This should interrupt Touch B In my delegate I put glView setMultipleTouchEnabled YES because I believe I need multiple touches enabled. In my CCLayer class with my added map and sprite I am using targeted touch delegate (i.e. ccTouchBegan NOT ccTouchesBegan, etc) I am accessing a touch object with touch event allTouches allObjects objectAtIndex 0 , however I don't have much understanding what index is considered the latest touch or even a process to always get the latest touch.
9
Cocos2D Upgrading from OpenGL ES 1.1 to 2.0 I have recently starting upgrading my ios game to the latest Cocos2D (2.0 rc), and I am having some difficulties upgrading my texture generation code to OpenGL 2.0. In the old version I generated images with this code CCRenderTexture rt CCRenderTexture renderTextureWithWidth WIDTH height HEIGHT rt beginWithClear bgColor.r g bgColor.g b bgColor.b a bgColor.a glDisable(GL TEXTURE 2D) glDisableClientState(GL TEXTURE COORD ARRAY) glVertexPointer(2, GL FLOAT, 0, verts) glColorPointer(4, GL FLOAT, 0, colors) glDrawArrays(GL TRIANGLE STRIP, 0, (GLsizei)nVerts) glEnableClientState(GL TEXTURE COORD ARRAY) glEnable(GL TEXTURE 2D) rt end But since OpenGL 2.0 works differently this code won't work. What is the best way to use the new OpenGL?
9
Cannot find the Cocos2d templates I am about to upgrade to the last version of Cocos2d and would like to uninstall my current Cocos2d templates before installing the new one but cannot find the templates to delete. I have looked at a number of web comments on this such as Uninstall Cocos2D ans another uninstall example but to no avail. However, I still see Cocos2d in my Xcode (4.5) framework. I have been searching my directories but cannot find it. Is there anyone out there who can give me a hint where to find it so i can delete in?
9
How can I cause the latest touch event to interrupt a prior event in Cocos2D? In Cocos2D for iPhone, I want the latest touch event to interrupt another and ignore the last touch. Let me know if I need to elaborate more, but basically my game consists of a lot of finger dragging, and if the player ever switched fingers, there may be some overlap, and for the way things are setup, it may detect it as a new touch. I think I have things almost on the right track, but my third touch does not work correctly. For instance Touch A begins and held Touch B begins and held Touch A let go Touch A begins and held lt This should interrupt Touch B In my delegate I put glView setMultipleTouchEnabled YES because I believe I need multiple touches enabled. In my CCLayer class with my added map and sprite I am using targeted touch delegate (i.e. ccTouchBegan NOT ccTouchesBegan, etc) I am accessing a touch object with touch event allTouches allObjects objectAtIndex 0 , however I don't have much understanding what index is considered the latest touch or even a process to always get the latest touch.
9
Rotating a sprite to touch I know this has been asked before and Ive looked through peoples questions and answers all over the internet and I just cant get it to work. Im sure its down to my inexperience. Ive got an arrow attached to a sprite, this sprite appears when touched but I want the arrow to point where the sprite will launch. I have had the arrow moving but it was very erratic and not pointing as it should. Its not moving at the moment but this is what I have. (void)update (ccTime)delta arrow.rotation dialRotation (void) ccTouchMoved (UITouch )touch withEvent (UIEvent )event pt1 self convertTouchToNodeSpace touch CGPoint firstVector ccpSub(pt, arrow.position) CGFloat firstRotateAngle ccpToAngle(firstVector) CGFloat previousTouch CC RADIANS TO DEGREES(firstRotateAngle) CGPoint vector ccpSub(pt1, arrow.position) CGFloat rotateAngle ccpToAngle(vector) CGFloat currentTouch CC RADIANS TO DEGREES(rotateAngle) dialRotation currentTouch previousTouch I have got pt from ccTouchBegan the same way as pt1 Thanks
9
Cocosdenshion and Android not working I'm trying to play sounds and music with cocos2d. When I run on iPhone and .caf files the audio is perfect, but on Android it is not playing the background music and is only playing 2 sounds of 10 files. I don't know what I'm doing wrong. include lt SimpleAudioEngine.h gt bool HelloWorld init() const char sound if CC TARGET PLATFORM CC PLATFORM IOS sound "Fun.caf" else sound "Fun.wav" endif auto audio CocosDenshion SimpleAudioEngine getInstance() audio gt preloadBackgroundMusic(sound) audio gt playBackgroundMusic(sound, true) audio gt setBackgroundMusicVolume(1.0f) void HelloWorld playSound() const char effect if CC TARGET PLATFORM CC PLATFORM IOS effect "Bomb.caf" else effect "Bomb.wav" endif audio gt preloadEffect(effect) audio gt playEffect(effect)
9
Remove HUD from Child Scene For my game, I create game scene for which I set HUD to it. First my game scene use BoundCamera, so I use hud to set score text, dollar text and setting button. Now on game scene when I touch on setting button, the child scene (setting scene) come up because I attached it to game scene. I use child scene because of pause resume functionality added to the setting scene. When child scene display on the screen at the same time hud content also displayed on the sceeen. But I don't want that hud content of my child scene (setting scene). From other post of this forum I found that made hud.setVisible(false). But this solution does not work for me because the touch area of hud's children remain active even though it were not displayed on the screen. So when player touch on these areas the effect of touch become available even if the hud is not displayed on the screen. Also I like to mention that my development platform is AndEngine. I hope someone give me best guidance on this.
9
How can I ensure I still get correct touch inputs when my scene is offset? How can I accept touch input beyond the scene's bounds, so that no matter what I set self.position to, touches can still be detected? I'm creating a tile based game from Ray Winderlich on Cocos2d version 3.0. I am at the point of setting the view of the screen to a zoomed in state on my tile map. I have successfully been able to do that although now my touches are not responding since I'm out of the coordinate space the touches used to work on. This method is called to set the zoomed view to the player's position (void)setViewPointCenter (CGPoint)position CGSize winSize CCDirector sharedDirector .viewSizeInPixels int x MAX(position.x, winSize.width 2) int y MAX(position.y, winSize.height 2) x MIN(x, ( tileMap.mapSize.width tileMap.tileSize.width) winSize.width 2) y MIN(y, ( tileMap.mapSize.height tileMap.tileSize.height) winSize.height 2) CGPoint actualPosition ccp(x, y) CGPoint centerOfView ccp(winSize.width 2, winSize.height 2) NSLog( "centerOfView ", NSStringFromCGPoint(centerOfView)) CGPoint viewPoint ccpSub(centerOfView, actualPosition) NSLog( "viewPoint ", NSStringFromCGPoint(viewPoint)) This changes the position of the helloworld layer scene so that we can see the portion of the tilemap we're interested in. That however makes my touchbegan method stop firing self.position viewPoint This is what the NSLog prints from the method 2014 01 30 07 05 08.725 TestingTouch 593 60b centerOfView 512, 384 2014 01 30 07 05 08.727 TestingTouch 593 60b viewPoint 0, 832 As you can see the y coordinate is 800. If i comment out the line self.position viewPoint then the self.position reads 0, 0 and touches are detectable again but then we don't have a zoomed view on the character. Instead it shows the view on the bottom left of the map. Here's a video demonstration. How can I fix this? Update 1 Here is the github page to my repository. Update 2 Mark has been able to come up with a temporary solution so far by setting the hitAreaExpansion to a large number like so self.hitAreaExpansion 10000000.0f This will cause touches to respond again all over! However, if there is a solution that would not require me to set the property with an absolute number then that would be great!
10
Which programming language to use for tools? I use C as my language as choice. However, I generally use Python to write helper utilities and tools. My worry is that as my game engine continues to grow it's getting tedious to reimplement some of its features in Python. There has got to be a better way. Here are the options as I seem them Keep on keeping on. That is often the answer in a cooperate environment. Maybe it has some merit. Build bindings for Python (yuck) and have it use pieces of the engine directly. Start building the tools using C instead. I already use QT in the Python tools to provide a GUI when needed. It doesn't seem like it'd be that much harder to use QT in C instead. However I'm worried my tool productivity will go down. I generally strive to apply much less rigidity in tool code than I would in shipping code. So what is common practice, use the same language for tools, or use a more RAD friendly one? What if you use a language that differs from the language of the game which do you use? How do tools interact with the game engine link to it directly or fake it?
10
What language and tools are good to start with for Linux game development? I would like to start learning about game development and I would like to do it using Linux. My main experience has been with Java and a bit of C , but that was for applications and not games. Now that I want to try with gaming, I'm wondering which IDE language should I use in Linux, whether I should go with C and compiling files manually at the beginning, or maybe continue with Java Eclipse, also I think I can use Eclipse with C , I have also started reading about Python... I was thinking in starting with the typical "Tetris" just to understand how a game works internally, and I think I can achieve that with all the previous options, but what do you recommend me or how have you started game developming under Linux?
10
Are bounding volumes created by artists? I'm interested in where in the tool chain bounding boxes are created. Are they made by the artists? In the modeling tool? How are they exported? Can Maya 3DS Max Blender ... mark geometry as bounding box? How does that work in Collada FBX?) Or is there a tool which calculates them? Are they calculated at run time? I basically know how bounding volumes work, but I'm a little bit confused on where to get them from.
10
What can I use to generate 2d vector graphics as a list of coordinates? I am working on a game that uses simple 2d vector graphics. I want a tool that will let me visually draw things like arbitrary polygons by placing points. A perfect tool would present a grid that I could scale larger or smaller (ie the window is 10 units across or the window is 20 units across). It would let me draw a polygon on this grid, and will tell me, simply, the coordinates of each point. It would be great if this tool could then export a file format that was something like 0, 5 3, 2 0, 0 3, 2 For bonus points, it would be great to be able to assign other attributes to each point. In the end, this will get passed to OpenGL, so things like color and opacity could possibly be used.
10
Good ways to edit arbitrary collision shapes for 2D physics engine? Assume you have several 1024x1024 textures which contain an arbitrarily shaped and relatively complex cave system whose walls need to have collision polygons defined. The polygons need to be convex to work with the physics engine. What kind of process and tools can you think of that would make editing the vertices of these walls as efficient and painless as possible? Especially considering that the polygons need to be convex, and the designer needs to see when that is not the case.
10
Image drawing tools (that aren't Photoshop) that work in the sRGB colorspace I'm looking for a way to create sRGB raster images. Now, I could use Inkscape and just have it render to a raster format, but are there any image drawing tools other than Photoshop that work in sRGB? Here's what I want to be able to do more specifically. Let's say the image is all one color. I want to be able to pick color 0x808080, which is in the sRGB colorspace. I want the file to write an image where every pixel is 0x808080. And then, when I read it, I can tell OpenGL that it's sRGB color data, so it will treat the 0x808080 color has being from the sRGB colorspace. The important part is that, when I'm selecting colors in the tool, the colors I'm selecting are from the sRGB colorspace.
10
Image drawing tools (that aren't Photoshop) that work in the sRGB colorspace I'm looking for a way to create sRGB raster images. Now, I could use Inkscape and just have it render to a raster format, but are there any image drawing tools other than Photoshop that work in sRGB? Here's what I want to be able to do more specifically. Let's say the image is all one color. I want to be able to pick color 0x808080, which is in the sRGB colorspace. I want the file to write an image where every pixel is 0x808080. And then, when I read it, I can tell OpenGL that it's sRGB color data, so it will treat the 0x808080 color has being from the sRGB colorspace. The important part is that, when I'm selecting colors in the tool, the colors I'm selecting are from the sRGB colorspace.
10
SFXR Like Tool for Speech Sfxr (and also Bfxr) is a great tool for generating sound effects for games. Is there something like this for speech synthesis? Not every game development tool and platform has a speech synthesis engine, and it would be great to at least get some decent sounding placeholders in place to see how the usability experience plays out. Even better if the results are tweakable, like sfxr. I'm looking for something I can at least run on windows, though preferably (like Bfxr) I would like a web application that I can just run out of my browser.
10
What can I use to generate 2d vector graphics as a list of coordinates? I am working on a game that uses simple 2d vector graphics. I want a tool that will let me visually draw things like arbitrary polygons by placing points. A perfect tool would present a grid that I could scale larger or smaller (ie the window is 10 units across or the window is 20 units across). It would let me draw a polygon on this grid, and will tell me, simply, the coordinates of each point. It would be great if this tool could then export a file format that was something like 0, 5 3, 2 0, 0 3, 2 For bonus points, it would be great to be able to assign other attributes to each point. In the end, this will get passed to OpenGL, so things like color and opacity could possibly be used.
10
Very easy game builders? Possible Duplicate What are some good game development programs for kids? I want very easy game builder for a kid somebody who knows nothing about programming games (how they work inside) and just wants to build some (I could teach him but I am not available all the time). She tried Adventure Maker and got confused. It has to be something very straightforward. Do You know about any? Thanks. )
11
anisotropic fog of war Here I am not talking about how to render fog of war, but how to model exploring of terrain in a more sophisticated way. In a straight forward approach, terrain explored by a game unit is simply represented by a circle whose radius is how far this unit can see. And visible area is just union of isometric circles. But I can tell that it is not the case in popular games. Please take a look at the following screenshot from League of Legends, for example. The sight of view is anisotropic. The shape of surrounding terrain is also taken in to account. Any idea how this can be done?
11
Rendering smooth ground I'm attempting to render terrain made out of a triangle mesh. The problem is that whenever I have a northwest gt southeast ramp in the terrain, I get this diamond pattern The issue is that at the top and bottom of the ramp, the terrain is more flat than at the middle, so if the ramp is aligned with the triangles, each triangle will have two light vertices (at the top and bottom), and one dark vertex (at the middle). How can I fix this effect? Subdividing the mesh helps, but doesn't fix it completely. Vertex shader uniform mat4 projection attribute vec3 position attribute vec3 normal attribute vec4 color varying vec3 f position varying vec3 f normal varying vec4 f color void main(void) gl Position projection position f color color f normal normal f position position Fragment shader varying vec3 f position varying vec3 f normal varying vec4 f color uniform vec3 light position void main(void) float light 0.5 0.5 abs(dot(normalize(f normal), normalize(light position f position))) gl FragColor vec4(light, light, light, 1) f color
11
Real world terrain import into UE4 I am trying to create a basic game in Unreal Engine 4.8.1 and I wish to have it set in the Dubai, UAE but i cannot find a way that will successfully use terrain data i have obtained (NASA Shuttle RADAR 90m) to create a 1 1 scale map in unreal without creating huge world spikes. Does anyone know a method that can import the data without creating terrain spikes?
11
How do I simplify terrain with tunnels or overhangs? I'm attempting to store vertex data in a quadtree with C , such that far away vertices can be combined to simplify the object and speed up rendering. This works well with a reasonably flat mesh, but what about terrain with overhangs or tunnels? How should I represent such a mesh in a quadtree? After the initial generation, each mesh is roughly 130,000 polygons and about 300 of these meshes are lined up to create the surface of a planetary body. A fully generated planet is upwards of 10,000,000 polygons before applying any culling to the individual meshes. Therefore, this second optimization is vital for the project. The rest of my confusion focuses around my inexperience with vertex data How do I properly loop through the vertex data to group them into specific quads? How do I conclude from vertex data what a quad's maximum size should be? How many quads should the quadtree include?
11
Mining cubes out of marching cubes I originally built the start of my game world with a fully minecraft style structure chunks, only visible faces rendered, noise, etc. Too blocky. I implement marching cubes. Looks great, horrible to work with The problem is when you try to add or remove blocks to the marching cubes as... exactly as they are supposed to... everything gets smoothed. It becomes difficult to raycast on a neighbor and if you do all the blocks around him get changed. Obviously. I see a lot of marching cubes metaball looking games that implement area based organic molding. You don't place "blocks" you shape an area or deshape it like Landmark mining etc. On the otherhand Blockscape and Landmark seem to be a blend of the two? The land starts out marching but you can cut clear square chunks out of it and place square cubes onto it. How can you make straight corners with marching cubes? Or is it a combination of two entirely different systems? (UPDATE) There is probably more than one answer to this, does anyone have any experience trying to do this though? I can think of a couple of possible approaches Separate player built objects into a separate mesh object per chunk keeping terrain as terrain. Run smoothing (marching cubes or others) algorithms and normal calculations only on terrain. Would probably need some sort of a half transparent cube highlighter showing what the cursor is currently selecting. I can see a number of benefits to this system, though feel as if there are some downsides I'm just not thinking of immediately that would crop up if I started coding it...? Define a "smooth" bool per cube, only assigned at initial calculation of the mesh on any surfaces (floor ceiling etc). Any built added removed blocks are not re labelled as "smooth" when generating the mesh use different math for smooth cubes than for blocky cubes. This is what I'm currently working with and it works, but it's still only about a third as smooth as a full marching cube approach would be. Basically I'm average each vertices y value with its surrounding four cubes height(noise) values while never letting it go beneath 0 or above 1 (to stay within the cube). I also had to re write the raycast click detection to use the surface normals. Re code the marching cubes algorithms to work only on the cells I want them to do what I want them to. This seems like the most difficult but possibly most visually rewarding approach. or ??
11
Quadtree vs multiple resolution grids for terrain rendering I have been thinking about quad trees with regards to terrain rendering. From my understanding the basic functionality of quadtree terrain rendering is to frustum cull the terrain in such a manner function render() lod threshold if(lod threshold reached !has children()) draw terrain mesh() return for(child in children) if(child.bounds.intersect(viewing frustum)) child.render() where node.bounds is a 3d bounds calculated as containing the maximum heightmap value of the contained terrain My questions are the following If we are in fact testing a 2d portion of terrain with it's bounds calculated to include the maximum heightmap value against the 3d frustum, what is the preferred bounds calculation for generating the node.bounds in the quadtree? That a tree is necessary because that one has to iterate every portion of a 3d scene to calculate frustum occlusion in a general way. Eg, there is no shortcut algorithm to calculate the set of 3d cells generated from a 2d grid that intersect the viewing frustum. As a more general question and to question the obvious, is there a way to calculate cells in a viewing frustum without having to iterate every cell in a scene? Presumably not otherwise you wouldn't need trees for culling With regards to an alternative grid implementation Has this implementation been contemplated for general purpose terrain culling? I am presuming that some form of grid base terrain culling is certainly preferred in certain games, namely top down games where the possibility of terrain in the distance of being on camera is non existent. function calc cells in quadrilateral(frustum projection onto 2d terrain grid) calculate cells in the resulting quadrilateral projection of the frustum onto the grid without having to bounds test every cell at some point based on distance from camera, assign lod retrieve lod for each cell in the calculated set from lod grids have multiple (array2 or intmap) containing the terrain data at every lod for O(1) retrieval Is there is a way to calculate cells in a quadrilateral without having iterate every cell in a grid? eg, from shaving off cells from slopes or something? If there is, in what fashion should one assign the lod cell based on distance? I haven't contemplated this in detail because 1 may be impossible The terrain would not be optimally culled in this 2d culling algorithm against the quadrilateral frustum projection onto the heightmap, because the height value at the edges may be outside the screen, correct? http www.olhovsky.com 2011 03 terrain started In this post, he describes assigning lod from a grid and from a quad tree. The illustrations are confusing with regards to whether question 1 is correct and terrain rendering with quad trees serves to draw the terrain mesh against the frustum as opposed to just as a function of distance 360 around the camera as at appears to do with his grid implementation. Please specify whether it appears that he is infact not frustum culling in the grid implementation but is frustum culling the quadtree.
11
3rd party terrain editor I am looking for a good application for generating 3d terrains (really allowing generation and then some user editing) . After a google search, I found many, but I need one that can export the entire terrain as a mesh. This, I was unable to find. (I need either a .obj .fbx or .3ds output) The size of the file that is written and the price of the program are not major factors in my decision.
11
3rd party terrain editor I am looking for a good application for generating 3d terrains (really allowing generation and then some user editing) . After a google search, I found many, but I need one that can export the entire terrain as a mesh. This, I was unable to find. (I need either a .obj .fbx or .3ds output) The size of the file that is written and the price of the program are not major factors in my decision.
11
Merging tesselated terrain with manually modelled In my flighsim visual system I am rendering large scale terrain using fixed grid mesh which is tesselated and displaced using height map. But for some relative small area (usually airports) we have much more detailed models including terrain, runways and so on. And here is a problem how can I merge tesselated terrain with modelled one? On the picture bellow grey is a tesselated terrain, and blue is modelled with 3dsmax.
11
Is 1 pixel of a height map representative of 1 vertex on the mesh? I'm trying to get my head around heightmap terrain generation. If I have a plane say 64 x 64 verts will I need to create a 64px by 64px greyscale heightmap in order to displace the geometry of the plane correctly?
12
What is the point of caling Draw() as often as possible? From the MSDN page Update and Draw are called at different rates depending on whether IsFixedTimeStep is true or false. If IsFixedTimeStep is false, Update and Draw will be called sequentially as often as possible. If IsFixedTimeStep is true, Update will be called at the interval specified in TargetElapsedTime, while Draw will continue to be called as often as possible. What is the point of calling Draw potentially more often than Update? Why is Draw not upper limited to the number of Update calls?
12
Third person camera xna I'm trying to create a third person camera in my XNA game. I'm able to move the model I have and the camera at the same time, although the camera is not "following" the model. The model moves faster than the camera. Ultimately, I want the camera to rotate with the model with the left and right keys, and move the model with forward and back. This is in my update method if (keyState.IsKeyDown(Keys.D)) camera.Rotation MathHelper.WrapAngle(camera.Rotation (rotateScale elapsed)) if (keyState.IsKeyDown(Keys.A)) camera.Rotation MathHelper.WrapAngle(camera.Rotation (rotateScale elapsed)) if (keyState.IsKeyDown(Keys.W)) camera.MoveForward(moveScale elapsed) player.Position new Vector3(0.1f, 0f, 0f) if (keyState.IsKeyDown(Keys.S)) camera.MoveForward( moveScale elapsed) player.Position new Vector3( 0.1f, 0f, 0f) player is the model I'm using. Currently the A and D keys don't do anything with the model. public class Camera private Vector3 position Vector3.Zero private Vector3 lookAt private Vector3 baseCameraReference new Vector3(0, 0, 1) private bool needViewResync true private float rotation public Matrix Projection get protected set private Matrix cachedViewMatrix public Vector3 Position get return position set position value UpdateLookAt() public float Rotation get return rotation set rotation value UpdateLookAt() public Matrix View get if (needViewResync) cachedViewMatrix Matrix.CreateLookAt(Position, lookAt, Vector3.Up) return cachedViewMatrix public Camera(Vector3 position, float rotation, float aspectRatio, float nearClip, float farClip) Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip) MoveTo(position, rotation) private void UpdateLookAt() Matrix rotationMatrix Matrix.CreateRotationY(rotation) Vector3 lookAtOffset Vector3.Transform(baseCameraReference, rotationMatrix) lookAt position lookAtOffset needViewResync true private void MoveTo(Vector3 position, float rotation) this.position position this.rotation rotation UpdateLookAt() public Vector3 PreviewMove(float scale) Matrix rotate Matrix.CreateRotationY(rotation) Vector3 forward new Vector3(0, 0, scale) forward Vector3.Transform(forward, rotate) return (position forward) public void MoveForward(float scale) MoveTo(PreviewMove(scale), rotation) I also want to offset the camera for obvious reason, but changing the values in the variable baseCameraReference doesn't change what I want it to
12
How can I load 2D texture data without a GraphicsDevice instance? We have a client server architecture for our game with the client being the XNA Game, and the game server is separate and only references XNA. They both use a shared DLL for networking. The game server is windows forms for just starting restarting and some stats output, and does no drawing or anything. The problem is I need to load Texture2D's on the game server, to get width height information, and for the server to be able to do per pixel collision detection for its simulation. However, it seems a Texture2D requires a GraphicsDevice to instantiate. And it appears a GraphicsDevice requires an XNA Game? Is there some way I can load a Texture2D into memory on the server without a graphics device, or some way to instantiate a GraphicsDevice to do this (even though nothing is going to be drawn)?
12
XNA maximum VertexBuffer size exception I am trying to build content(a text file contains list of triangles vertices) for an XNA application through a custom pipeline importer. It works ok. But when number of triangles gets near 1m(in this case 946612 triangle amp 303112 unique vertex) I get this error "XNA Framework HiDef profile supports a maximum VertexBuffer size of 67108863, but this VertexBuffer is 68847328." 1 Is this number in bytes or just the number of vertices? I assume bytes which would make it 1.3m vertex. 2 The VertexBuffer size, Does it refer to the MeshContent Position collection or the GeometryContent VertexContent or the Model.Meshes i .MeshParts i .VertexBuffer.VertexCount? The reason is that the MeshContent Position collection holds unique vertices whereas the other, all of the triangles vertices which might have duplicates. ex. For a simple cube, the Position collection holds 8 vertex and the VertexContent have 36(12 tri 3) vertex which have duplicates. Once the MeshBuilder.FinishMesh() method is called it reduces to 24 vertex. Why 24? And this is exactly the number that Model.Meshes i .MeshParts i .VertexBuffer.VertexCount shows at the runtime. 3 Also, does this error regards only one mesh exceeding certain limit in vertex size or the whole Model.Meshes, or could be both? Any help to understand how these things work is appreciated.
12
Alpha From PNGs Butchered I have a pretty vanilla Monogame game. I'm using PNG for all my sprites (made in Photoshop). I noticed that XNA is butchering the aliasing no matter what I do, my graphics appear jaggedy. Below is a screenshot. The bottom half is what XNA shows me when I zoom in 2X using a Matrix on my GraphicsDevice (to make the effect more obvious). The top is when I pasted the same sprites from Photoshop and scaled them to 200 . Note that partially transparent pixels are turning whiteish. Is there a way to fix this? What am I doing wrong? Here's the relevant call to draw to the SpriteBatch spriteBatch.Draw(this.texture, this.positionVector, null, Color.White, this.Angle, this.originVector, 1f, SpriteEffects.None, 0f) (this.positionVector can easily be Vector.Zero Color.White as 100 alpha, I think this.Angle can be a real angle (small gt in the image) or zero (the orb itself).
12
How to calculate the position of an attached model after rotation? I'm programming a basic game on XNA. I started to place an object (eg weapon) attached to the right arm of my player. When I move my character forward behind left or right all right. But when I rotates my equipment is not positioned correctly. I am fully understands it is necessary to recalculate the new position based on the rotation done but I do not see how. Here is my code and pictures Function that will draw the current item selection in the player's hand private void draw itemActionInUse(Model modelInUse) int handIndex skinningData.BoneIndices "Hand Right" Matrix worldTransforms animationPlayer.GetWorldTransforms() Matrix rotationMatrixCalcul Matrix.CreateRotationY(player.Rotation.Y) Here I calculate the new position of the item, but it does not work Vector3 newPosition Vector3.Transform(new Vector3(player.Position.X, player.Position.Y 4, player.Position.Z ), rotationMatrixCalcul) foreach (ModelMesh mesh in modelInUse.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.World worldTransforms handIndex Matrix.CreateScale(2) Matrix.CreateRotationY(player.Rotation.Y) Matrix.CreateTranslation(newPosition) effect.View View effect.Projection Projection effect.EnableDefaultLighting() mesh.Draw() Figure A position x 0 y 0 z 0 angle 90 Figure B position x 2 y 4 z 0 angle 90 Figure A position x 1 y 0 z 1 angle 35 Figure B position How calcul this position ? angle 35
12
Viewport.Unproject Checking if a model intersects a large sprite Let's say I have a sprite, drawn like this spriteBatch.Draw(levelCannons i .texture, levelCannons i .position, null, alpha, levelCannons i .rotation, Vector2.Zero, scale, SpriteEffects.None, 0) Picture levelCannon as being a laser beam that goes across the entire screen. I need to see if my 3d model intersects with the screen space inhabited by the sprite. I managed to dig up Viewport.Unproject, but that seems to only be useful when dealing with a single point in 2d space, rather than an area. What can I do in my case?
12
HLSL Offset and length were out of bounds Vertex Shader Constants float4x4 World float4x4 View float4x4 Projection float4x4 WorldViewIT Color Texture texture Texture Normal Texture texture NormalMap Specular Texture texture SpecularMap Albedo Sampler sampler AlbedoSampler sampler state texture lt Texture gt MINFILTER LINEAR MAGFILTER LINEAR MIPFILTER LINEAR ADDRESSU WRAP ADDRESSV WRAP NormalMap Sampler sampler NormalSampler sampler state texture lt NormalMap gt MINFILTER LINEAR MAGFILTER LINEAR MIPFILTER LINEAR ADDRESSU WRAP ADDRESSV WRAP SpecularMap Sampler sampler SpecularSampler sampler state texture lt SpecularMap gt MINFILTER LINEAR MAGFILTER LINEAR MIPFILTER LINEAR ADDRESSU WRAP ADDRESSV WRAP Vertex Input Structure struct VSI float4 Position POSITION0 float3 Normal NORMAL0 float2 UV TEXCOORD0 float3 Tangent TANGENT0 float3 BiTangent BINORMAL0 Vertex Output Structure struct VSO float4 Position POSITION0 float2 UV TEXCOORD0 float3 Depth TEXCOORD1 float3x3 TBN TEXCOORD2 Vertex Shader VSO VS(VSI input) Initialize Output VSO output Transform Position float4 worldPosition mul(input.Position, World) float4 viewPosition mul(worldPosition, View) output.Position mul(viewPosition, Projection) Pass Depth output.Depth.x output.Position.z output.Depth.y output.Position.w output.Depth.z viewPosition.z Build TBN Matrix output.TBN 0 normalize(mul(input.Tangent, (float3x3)WorldViewIT)) output.TBN 1 normalize(mul(input.BiTangent, (float3x3)WorldViewIT)) output.TBN 2 normalize(mul(input.Normal, (float3x3)WorldViewIT)) Pass UV output.UV input.UV Return Output return output Pixel Output Structure struct PSO float4 Albedo COLOR0 float4 Normals COLOR1 float4 Depth COLOR2 Normal Encoding Function half3 encode(half3 n) n normalize(n) n.xyz 0.5f (n.xyz 1.0f) return n Normal Decoding Function half3 decode(half4 enc) return (2.0f enc.xyz 1.0f) Pixel Shader PSO PS(VSO input) Initialize Output PSO output Pass Albedo from Texture output.Albedo tex2D(AlbedoSampler, input.UV) Pass Extra Can be whatever you want, in this case will be a Specular Value output.Albedo.w tex2D(SpecularSampler, input.UV).x Read Normal From Texture half3 normal tex2D(NormalSampler, input.UV).xyz 2.0f 1.0f Transform Normal to WorldViewSpace from TangentSpace normal normalize(mul(normal, input.TBN)) Pass Encoded Normal output.Normals.xyz encode(normal) Pass this instead to disable normal mapping output.Normals.xyz encode(normalize(input.TBN 2 )) Pass Extra Can be whatever you want, in this case will be a Specular Value output.Normals.w tex2D(SpecularSampler, input.UV).y Pass Depth(Screen Space, for lighting) output.Depth input.Depth.x input.Depth.y Pass Depth(View Space, for SSAO) output.Depth.g input.Depth.z Return Output return output Technique technique Default pass p0 VertexShader compile vs 3 0 VS() PixelShader compile ps 3 0 PS() This is my current shader it is producing a "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection" argumente axeception I don't understand what's wrong with it . Any help is appreciated.
12
Using XNA to create an isometric tileset? In XNA, how can I take any given texture, then render it so that it fits completely into a 64x31 (or 32x15) isometric tile such that it tessellates perfectly? My goal is to give various textures to my game, then have it generate an isometric tileset from the given textures, thus requiring pixel perfect accuracy. I have tried to use an orthogonal projection, which has good (but imperfect) results, but always ends up making odd width textures instead, such as 61x29 no amount of adjusting the camera position or target or orthagonal settings seems to correct this, textures always end up with 1, 3, or 5 pixels on the top or bottom of the tile How can I correct this behavior, or is there a better way I can create multiple isometric tiles easily? Edit Before anyone asks, I'm not trying to clip or mask anything when I render it. I'm trying to preserve as much of the texture as possible and push it cleanly into a specific space.
12
Feasibility of an XNA game on PC A friend and I are doing a 2D XNA game. Thus far, the API seems really cool and performance is acceptable. My question is more towards the release of it though. As other developers how have done games, how well have they done for you on PC (as far as downloads, sales, etc)? I know the statistics about the Xbox360 from seeing it personally but, I was curious as to how successful these were on PC?
12
Rendering tiles on 3 4 perspective Using a 3 4th perspective, I'm trying to create a way to render cliffs where nothing is overlapped, and it creates an accurate representation of the elevation. This is a rough mockup of how it might look in game The way the tile data is organized is by layer. Each elevation has a layer class which holds all of the ground data for that specific layer, and all unoccupied space is simply null in the array. I can't seem to come up with a way to render the data so it would look something like this. I've thought about rendering from highest to lowest elevation, the other way around, etc. All entailed a situation where something is getting overlapped that shouldn't be. What's the best way to do this?
12
How exactly does XNA's SpriteBatch work? To be more precise, if I needed to recreate this functionality from scratch in another API (e.g. in OpenGL) what would it need to be capable of doing? I do have a general idea of some of the steps, such as how it prepares an orthographic projection matrix and creates a quad for each draw call. I'm not too familiar, however, with the batching process itself. Are all quads stored in the same vertex buffer? Does it need an index buffer? How are different textures handled? If possible I'd be grateful if you could guide me through the process from when SpriteBatch.Begin() is called until SpriteBatch.End(), at least when using the default Deferred mode.
12
Model in Blender GLSL to XNA HLSL Is it possible to make model in Blender, with enabled GLSL, add multiple textures, etc, and then just load it in XNA, where's own HLSL? Will it work?
12
Pitch camera around model Currently, my camera rotates with my model's Y Axis (yaw) perfectly. What I'm having trouble with is rotating the X Axis (pitch) along with it. I've tried the same method for cameraYaw() in the form of cameraPitch(), while adjusting the axis to Vector.Right, but the camera wouldn't pitch at all in accordance to the Y Axes of the controller. Is there a way similar to this to get the same effect for pitching the camera around the model? Rotates model on its own Y axis public void modelRotMovement(GamePadState pController) Yaw pController.ThumbSticks.Right.X MathHelper.ToRadians(speedAngleMAX) AddRotation Quaternion.CreateFromYawPitchRoll(Yaw, 0, 0) ModelLoad.MRotation AddRotation MOrientation Matrix.CreateFromQuaternion(ModelLoad.MRotation) Orbit (yaw) Camera around model (camTarget is the model's position) public void cameraYaw(Vector3 axis, float yaw) ModelLoad.CameraPos Vector3.Transform(ModelLoad.CameraPos ModelLoad.camTarget, Matrix.CreateFromAxisAngle(axis, yaw)) ModelLoad.camTarget public void updateCamera() cameraYaw(Vector3.Up, Yaw)
12
How to go from Texture2DContent to Texture2D in a content processor? I'm using reflection to create a manifest of all assets, strongly typed. It's working fine for my own types I get the type of the asset, if a processor is ran on it I get the output type. Then I check to see if there's a ContentSerializerRuntimeTypeAttribute applied to the type. If so, then I get the RuntimeType value and do a Type.GetType() to get the type back. The problem I have is if the type is Texture2DContent (for example) as that doesn't have the ContentSerializerRuntimeTypeAttribute. How can I go from a Type representing Texture2DContent to a Type representing Texture2D? I know I can just check for EndsWith("Content") as a last resort, but how to I get the namespace qualified type so I can get my Type object?
12
I'm having trouble with collision detection in XNA I've written a tile editor and game in XNA, with velocities and gravity, and am having trouble with some of my collision detection things. It works okay, but seems to glitch between just inside and outside the tile the player is on. Here's my collision detection function and the other functions it uses void SolveCollisions(List lt Tile gt tiles, Vector2 screensize) if (position.X lt 0) position.X 0 if (position.X 32 gt screensize.X) position.X screensize.X 32 if (position.Y lt 0) position.Y 0 if (position.Y 32 gt screensize.Y) position.Y screensize.Y 32 foreach (Tile t in tiles) if (absTilePos(position.X) absTilePos(t.position.X)) if (intersect(position.Y, t.position.Y, 32, 32)) if (position.Y gt 0) velocity.Y 0 position.Y tilePos(position.Y) if (position.Y lt 0) velocity.Y 0 position.Y tilePos(position.Y) 32 if (absTilePos(position.Y) absTilePos(t.position.Y)) if (intersect(position.X, t.position.X, 32, 32)) if (position.X gt 0) velocity.X 0 position.X tilePos(position.X) if (position.X lt 0) velocity.X 0 position.X tilePos(position.X) 32 bool intersect(float p1, float p2, float s1, float s2) if (p1 lt p2 amp amp p1 s1 gt p2) return true if (p2 lt p1 amp amp p2 s2 gt p1) return true return false float tilePos(float f) int i (int)f i 32 i 32 return (float)i float absTilePos(float f) int i (int)f i 32 return (float)i The player also glitches into blocks on it's top and right ( http puu.sh 2cVQf ) when it hits them instead of bouncing off them it just goes straight into them. Does anyone know how to remedy this? Thanks!
12
Performance architectural implications of calling SpriteBatch.Begin End in many different places? I notice some code samples only call SpriteBatch.Begin and SpriteBatch.End in the game's main draw method and then draw everything within that method through direct SpriteBatch.Draw calls or indirect calls through method calls from other classes that store a reference to the SpriteBatch object and then use its Draw method. Another approach I see is that in these separate classes they call SpriteBatch.Begin and SpriteBatch.End before their drawing code in each of these classes and don't rely on already being contained within a drawing session (between a begin and end call). My question is two fold. Firstly, as the title suggests, what are the performance implications of calling SpriteBatch.Begin End in all these separate classes so often (once per class per drawing update) versus just calling it the one time each update. Secondly, and this question is a a bit more subjective but, which design is generally preferable? Thanks.
12
XNA MonoGame SharpDX Pixel shader with sprite sheet I've searched around for two days now on the internet but cannot find a solution. I've also read up on Pixel Shaders on MSDN with no luck. I'm trying to apply a simple pixel shader to a sprite batch for alpha masking. It worked fine when I used two separate textures one for the sprite and a matching one for the shader. Problem is I don't want to do this. I'd like to use my sprite sheet and source rectangle and use a separate mask from a sprite sheet of masks. However it doesn't work. The sprite draw perfectly but the mask does not and appears to be using a sprite at a different locating in the mask sheet. It has something to do with getting the coordinates of the mask. My idea was if the sprite to draw was at 200 200 in the sheet, subtract the correct tex coordinates from it to get the pixel, then add this to the mask. pos texCoord sprite start offset mask start location of mask from current pixel EG pos 200 200 200 200 0 maskPos 440 330 pos 201 201 200 200 1 maskPos 441 330 UPDATE It is definitely converting the coordinates of the sprite to the mask that is the issue. I've tried numerous methods to try and convert this and normalize the coordinates to singles with no luck. The result after masking The mask being applied The actual mask that should be applied I have no idea why the result is being botched and section cut out like shown in image one. 22 is the width and height of both masks and sprites. 512 is the width and height of both sprite sheets. To calculate the pos in the mask that generate the botch float maskPixelX (inCoord.x 512) X pos to draw the tile float maskPixelY (inCoord.y 512) X pos to draw the tile float2 maskCoord float2((maskPixelX maskpos.x) 22, (maskPixelY maskpos.y) 22) Pixel shader uniform extern texture ScreenTexture sampler screen sampler state Texture lt ScreenTexture gt uniform extern texture MaskTexture sampler mask sampler state Texture lt MaskTexture gt float2 startpos float2 maskpos float4 PixelShaderFunction(float2 inCoord TEXCOORD0) COLOR Get the matching pixel offset in mask. float2 pos inCoord startpos pos pos maskpos float4 color tex2D(screen, inCoord) float4 color2 tex2D(mask, pos) if (color2.a gt 0) color.rgba 0 return color technique pass P0 PixelShader compile ps 2 0 PixelShaderFunction() And here is the draw call mask.Parameters("MaskTexture").SetValue(maskSheet) ' Sprite sheet with mask. mask.Parameters("startpos").SetValue(New Vector2(200, 200)) mask.Parameters("maskpos").SetValue(New Vector2(440, 330)) ' Postion of mask in sheet. Dim source As New Rectangle(200, 300, 22, 22) spriteBatch.Draw(sprites, Vector2.Zero, source, Color.White, 0.0F, New Vector2(0, 0), 1.0F, SpriteEffects.None, 1.0F)
12
XBOX Xna ! DirectX? I'm a bit confused. The question is when I'm developing a XNA game for Xbox (or Windows), is it possible to use DirectX (to make use of the GPU)? Or is everything getting calculated by the CPU? A quick Google search didn't gave any results of combining those two...
12
Positioning a sprite in XNA Use ClientBounds or BackBuffer? I'm reading a book called "Learning XNA 4.0" written by Aaron Reed. Throughout most of the chapters, whenever he calculates the position of a sprite to use in his call to SpriteBatch.Draw, he uses Window.ClientBounds.Width and Window.ClientBounds.Height. But then all of a sudden, on page 108, he uses PresentationParameters.BackBufferWidth and PresentationParameters.BackBufferHeight instead. I think I understand what the Back Buffer and the Client Bounds are and the difference between those two (or perhaps not?). But I'm mighty confused about when I should use one or the other when it comes to positioning sprites. The author uses for the most part Client Bounds both for checking whenever a moving sprite is of the screen and to find a spawn point for new sprites. However, he seems to make two exceptions from this pattern in his book. The first time is when he wants some animated sprites to "move in" and cross the screen from one side to another (page 108 as mentioned). The second and last time is when he positions a texture to work as a button in the lower right corner of a Windows Phone 7 screen (page 379). Anyone got an idea? I shall provide some context if it is of any help. Here's how he usually calls SpriteBatch.Draw (code example from where he positions a sprite in the middle of the screen page 35 ) spriteBatch.Draw(texture, new Vector2( (Window.ClientBounds.Width 2) (texture.Width 2), (Window.ClientBounds.Height 2) (texture.Height 2)), null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0) And here is the first case of four possible in a switch statement that will set the position of soon to be spawned moving sprites, this position will later be used in the SpriteBatch.Draw call (page 108) Randomly choose which side of the screen to place enemy, then randomly create a position along that side of the screen and randomly choose a speed for the enemy switch (((Game1)Game).rnd.Next(4)) case 0 LEFT to RIGHT position new Vector2( frameSize.X, ((Game1)Game).rnd.Next(0, Game.GraphicsDevice.PresentationParameters.BackBufferHeight frameSize.Y)) speed new Vector2(((Game1)Game).rnd.Next( enemyMinSpeed, enemyMaxSpeed), 0) break
12
What are some great and useful resources for an Isometric game built on the XNA Framework? I'm currently working on an isometric game using the Microsoft XNA Framework. I'm looking of resources that would be of use for making this a successful project, such as isometric engines, physics engines, sprite engines(for isometric games), event handlers for ... Any input would be greatly appreciated.
12
2D Simplex Smooth Cave Generation So I'm creating a system of caves below my random terrain generation, and I'm using 2D Simplex Noise to do so and I have a pretty good grasp on generating the random caves. However, the cutoff from the terrain to where the cave layer starts is a bit abrupt, and I was wondering how I could prevent this. Random Level Generation public static Level GetRandomLevel(int rows, int cols, float scale 1f) Tile tiles new Tile rows for (int i 0 i lt rows i ) tiles i new Tile cols for (int x 0 x lt cols x ) tiles i x new Tile(0, new Vector2(x, i), scale) int left Main.rand.Next(rows 4, rows 2) double seed Main.rand.NextDouble() 255 for (int i 0 i lt cols i ) float noise Noise.Generate((float)seed) noise 7 int height left (int)noise height (int)MathHelper.Clamp(height, 0, rows 1) tiles height i new Tile(2, new Vector2(i, height), scale) FillLower(tiles, height, i, scale) seed .05f int heightmap new int cols for (int i 0 i lt cols i ) for (int j 0 j lt rows j ) if (tiles j i .TileID 2) heightmap i j break Smoothing out terrain for (int i 0 i lt cols 1 i ) if (heightmap i gt heightmap i 1 ) tiles heightmap i 1 i new Tile(6, new Vector2(i, heightmap i 1), scale) tiles heightmap i i new Tile(3, new Vector2(i, heightmap i ), scale) for (int i cols 1 i gt 0 i ) if (heightmap i gt heightmap i 1 ) tiles heightmap i 1 i new Tile(5, new Vector2(i, heightmap i 1), scale) tiles heightmap i i new Tile(4, new Vector2(i, heightmap i ), scale) Caves for (int y 0 y lt rows amp amp left 10 y lt rows y ) for (int x 0 x lt cols x ) double noise Noise.Generate(x (70 scale), (y 1) (70 scale)) Not air if (tiles left 10 y x .TileID ! 0 amp amp noise gt 0) tiles left 10 y x new Tile(0, new Vector2(x, left 10 y), scale) return new Level(tiles) Here is a picture demonstrating what I mean about the 'cave layer cutoff' being to abrupt.
12
Rotate the camera around the model in XNA? How can I rotate my view around a model? My model has a rotation. If this rotation changed, my view should also change. The camera should be behind the model everytime. Thank you very much!
12
What's the difference between XNA Game Services and glorified global variables? The Microsoft.Xna.Framework.Game class has a Services property that allows the programmer to add a service to their game by providing the type of the class and an instance of the class to the Add method. Now, instead of having to pass an AudioComponent to all classes and methods that require it, instead you just pass your Game instance and look up the service. (Service Locator) Now, because games have many services (GraphicsDevice, SceneGraph, AudioComponent, EffectsManager, et cetera), you will now basically be passing Game to everything. So why not just make these instances a Singleton? Well, because Singletons are bad because they have a global state, prevent testing, and make your design much more brittle. Service locators are equally considered to be an anti pattern to many because instead of just passing the dependency to an object, you pass a service locator (the Game) which couples that class with the rest of the services. So then why are Services recommended in XNA and game development? Is it because games are different from regular programs and are highly intertwined with their components and having to pass every component necessary for the functioning of a class would be highly cumbersome? Are Game Services just then a necessary evil in game design? Are there alternatives that don't involve lengthy parameter lists and coupling?
12
x axis detection issues platformer starter kit I've come across a problem with the collision detection code in the platformer starter kit for xna.It will send up the impassible flag on the x axis despite being nowhere near a wall in either direction on the x axis, could someone could tell me why this happens ? Here is the collision method. lt summary gt Detects and resolves all collisions between the player and his neighboring tiles. When a collision is detected, the player is pushed away along one axis to prevent overlapping. There is some special logic for the Y axis to handle platforms which behave differently depending on direction of movement. lt summary gt private void HandleCollisions() Get the player's bounding rectangle and find neighboring tiles. Rectangle bounds BoundingRectangle int leftTile (int)Math.Floor((float)bounds.Left Tile.Width) int rightTile (int)Math.Ceiling(((float)bounds.Right Tile.Width)) 1 int topTile (int)Math.Floor((float)bounds.Top Tile.Height) int bottomTile (int)Math.Ceiling(((float)bounds.Bottom Tile.Height)) 1 Reset flag to search for ground collision. isOnGround false For each potentially colliding tile, for (int y topTile y lt bottomTile y) for (int x leftTile x lt rightTile x) If this tile is collidable, TileCollision collision Level.GetCollision(x, y) if (collision ! TileCollision.Passable) Determine collision depth (with direction) and magnitude. Rectangle tileBounds Level.GetBounds(x, y) Vector2 depth RectangleExtensions.GetIntersectionDepth(bounds, tileBounds) if (depth ! Vector2.Zero) float absDepthX Math.Abs(depth.X) float absDepthY Math.Abs(depth.Y) Resolve the collision along the shallow axis. if (absDepthY lt absDepthX collision TileCollision.Platform) If we crossed the top of a tile, we are on the ground. if (previousBottom lt tileBounds.Top) isOnGround true Ignore platforms, unless we are on the ground. if (collision TileCollision.Impassable IsOnGround) Resolve the collision along the Y axis. Position new Vector2(Position.X, Position.Y depth.Y) Perform further collisions with the new bounds. bounds BoundingRectangle This is the section which deals with collision on the x axis else if (collision TileCollision.Impassable) Ignore platforms. Resolve the collision along the X axis. Position new Vector2(Position.X depth.X, Position.Y) Perform further collisions with the new bounds. bounds BoundingRectangle Save the new bounds bottom. previousBottom bounds.Bottom
12
How do I detect and remove completed rows of blocks in Tetris? I am making Tetris for a learning experience in XNA, and I'm having trouble deleted completed rows. I am having an issue with deleting rows, for some reason when I go to delete a row, I end up creating more blocks or not deleting all of the blocks in the row. The method I am using to detect and remove blocks is as follows 'rowCount' is an int 20 holding the number of blocks in each row (my playing field is 20 rows tall and 10 blocks wide). for (int i 0 i lt rowCount.Length i ) if (rowCount i gt 10) The row is full, remove the blocks. 'blocks' is a list of all blocks that have settled. for (int j 0 j lt blocks.Count j ) if (blocks j .Row i) If the settled block is in this row, remove it. blocks.RemoveAt(j) rowCount i Move any blocks above the now empty row down one row. foreach (Block b in blocks) if (b.Row lt i) b.Row rowCount b.Row This is done in my main Update method after I've determined if the current block has settled or not. As implemented, this algorithm will usually end up recording more than ten blocks in some rows and will not correctly clear completed rows and move the rows above down one unit. Why is this, and what can I do to fix the algorithm?
12
How could an XNA game close with no exception being thrown? I've been messing with my game's network code recently (TCP UDP sockets) and my game keeps shutting down with no exceptions being thrown at all. It runs fine until the disconnection of a client, so I already know that it has to be related to the network. My real problem is that no exception is thrown and the game silently exits on both the client and server sides. How's that even possible? What could end the runtime of an XNA game?
12
Is it Possible to create one equipment piece, and handle the manipulation programatically I have a 2D game made in XNA 4.0. I am brainstorming on how to implement a system of equipment where I can draw one Texture, and rotate scale it to my character's current animation without haveing to create a seperate Atlas for each Weapon Gear Piece. Right Now I have a Default Character Sprite Sheet that I use, and For each Item I wish to incorporate into the game, I draw it onto the Sprite Sheet, remove the character from the sprite sheet, then draw the new Sprite Sheet with just the visible parts of the given piece of equipment. It works very well, and looks great... The only problem is that It requires a lot of work for each piece of gear I implement into the game. Originally my hope was to Create one image, and have a system in place that can alter the texture as required to rotate and move with my hero's animations. Since I am in 2D, I am restricted to Scaling and rotation images. Is this goal of creating one image even a possibility? If so I would love any direction to as how this might be achieved.
12
Implementing a Custom Mouse Cursor in XNA I have tried making a custom mouse cursor, hiding the real mouse, taking the real mouse delta and clamping it to a maximum speed. Here is the problem In windowed mode, the "real" mouse cursor moves off the window while the custom mouse cursor (since it's movement is being scaled) is still somewhere inside the game window. This becomes bizarre and is obviously not desired, as clicking at this point means clicking on things outside the game window. Is there any way to accomplish this in windowed mode? In fullscreen mode, the "real" mouse cursor is bounded to the edges of the screen. So I get to a point where there is no more mouse delta, yet my custom cursor is still somewhere in the middle of the screen and hence can't move further in that direction. If I wanted to clamp it to the edge of the screen when the real cursor is at the edge, then I would get an abrupt jump to the edge of the screen, which isn't desired either Any help would be appreciated. I'd like to be able to limit the speed of the mouse.
12
What is the point of the XNA.Input.Button enum? I am trying to make an InputManager class that will let me basically bridge XNA's various input methods and do a corresponding action in my game. Part of this is designing different keybindings. Suppose I have a class GamePadBinding InputBinding lt Button gt this is the Button enum from XNA.Input and has a variety of different buttons (Left, A, etc). However, to actually check input, I have to call something like if (GamePad.GetState(PlayerIndex.One).DPad.Left ButtonState.Pressed), and the problem with that is that it uses a struct with readonly values. How am I expected to store an enum of type Button and compare that with this? I really am not seeing the point of this enum.
12
Stacking items, c XNA When item reaches maximum stack, new items added are also maximum stack haven't used this site before so I'm sorry if I format my post badly. I am trying to build a stackable inventory for my game in c XNA and the problem I've encountered is when an item in my inventory reaches the maximum stackable count (10) and creates a second instance of the item in the second slot of my inventory the second instance retains the count value of the first item. So 10 items in my inventory have a value of 10 in the first slot, but 11 items will have a value of 10 in slot 1 and 10 in slot 2 4 pictures illustrating my problem http imgur.com a KZ5EL class Backpack 25 Inventory Slots public int itemMax 25 public List lt Items gt ItemList new List lt Items gt () int end 1 Funtction to add new items public void Add(Items newItem) if (ItemList.Count lt itemMax) this if statement makes a list item add if the list.count is zero if (ItemList.Count lt end) ItemList.Add(newItem) for (int x 0 x lt ItemList.Count x ) if (ItemList x .nameID newItem.nameID) Checks for stackable item and less than 10 counts of item if (ItemList x .isStackable amp amp ItemList x .Count lt 10) ItemList x .Count 1 break else ItemList.Add(newItem) end 1 break else ItemList.Add(newItem) end 1 EDIT for floAr I access the function like this Items i i new Items() i.nameID 1 i.Name "Hog Meat" i.Item ItemClass.Useable i.Description "Regenerates 30 hunger." i.isStackable true i.Image Content.Load lt Texture2D gt ("hogmeat") i.sRect new Rectangle(0, 0, 16, 16) backpack.Add(i)
12
How can I implement scrolling endless road in XNA? I am developing XNA game like following screenshot. I created my 3D objects and camera so I have models. But how can I implement scrolling road in XNA?
12
Orienting a model to face a target I have two objects (target and player), both have Position (Vector3) and Rotation (Quaternion). I want the target to rotate and be facing right at the player. The target, when it shoots something should shoot right at the player. I've seen plenty of examples of slerping to the player, but I don't want incremental rotation, well, I suppose that would be ok as long as I can make the slerp be 100 , and as long as it actually worked. FYI Im able to use the position and rotation to do plenty of other things and it all works great except this last piece I cant figure out. Code samples run in the Target's class, Position the targets position, Avatar the player. EDIT Im now using Maik's c code he has provided and it works great!
12
How do i create bounding boxes with XNA 4.0? I am having some trouble making bounding boxes for my models I am using within XNA 4.0. The way it was done in XNA 3.1 seems to be obsolete as you can no longer access parameters that were used before in XNA 3.1. Has anyone got any decent links I have been looking around the net for a while now and all I am finding is things for XNA 3.1 or below. Help much apprechiated. Regards Mark EDIT Hey, the problem i am having is getting the min and max points for my model i load through the content pipeline. as articles i have seen on how to do it tell you to do such things as VertexPositionNormalTexture vertices new VertexPositionNormalTexture mesh.VertexBuffer.SizeInBytes mesh.MeshParts 0 .VertexStride but i can no longer call size in bytes and vertex strides within XNA 4.0
12
How do you do AI path following within a 2d physics engine like farseer box2d? I'm in the process of moving a 2d top down game I've been working on into a proper rigid body physics engine like Farseer. Up until now, I had just hacked together my own physics code where needed. I'm trying to learn the proper way of doing things here. What is the proper way to make your AI follow a set path once you have made them rigid bodies inside of the physics engine? If I have a path of navigation nodes on my map that I need the AI to follow, previously I would just move them along the path manually by calculating the next position they should be at for the next time step and manually setting them to that position. But now they are rigid bodies and subject to collisions and any forces that may hit them and knock them off path. So to make the AI move I believe I should now be applying impulses forces to them? I should no longer be manually setting their position each frame. So I think I need to go from a deterministic world where I force the AI to strictly follow a path to a non deterministic world where they could get knocked about in any direction if hit and I simply nudge them towards the next node in the path to make them move. Is that right? Is that how other people do it? This raises some questions about how to then avoid your AI getting stuck on corners of scenery now that they aren't walking a precise path, how do you guys handle that type of thing? Or is it better to somehow mix the two and still have your AI follow a fixed path by setting their position manually, and only react to other forces under certain circumstances you can easily control? Thanks for any advice guys.
12
How can I implement 2D cel shading in XNA? So I was just wondering on how to give a scene I am rendering a hand drawn look (like say Crayon Physics). I don't really want to preprocess the sprites and was thinking of using a shader. Cel shading supplies the effect I want to achieve, but I am only aware of the 3D instances for it. So I wanted to ask if anyone knew a way to get this effect in 2D, or if cel shading would work just as fine on 2D scenes? Edit The reason why i didn't want to do preprocessing ,was that i almost don't have anything to prepossess.I have some material textures ,which are basically just black and white images and using them i create textures from specific vertices ,which represent entities in the game (mostly physics based ones).So i wasn't sure how to processes the textures for the texture mapping to work as i intended.Thanks for the help!
12
XNA Multiple Key Input I'm using the KeyboardState state way (if there are any others) of handling key presses for a PC game. It has been working fine for single key presses but now I am trying to handle multiple key presses at once. I have it grab the newState at the top and then save it to the oldState at the bottom. I've tried it this way if (newState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.D2) amp amp newState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftAlt)) if (equipment accessory2 ! null) UseItem(equipment accessory2, "Accessory 2") And I've also tried Microsoft.Xna.Framework.Input.Keys currentPressedKeys newState.GetPressedKeys() bool altPressed false, twoPressed false for (int i 0 i lt currentPressedKeys.Length i ) if (currentPressedKeys i Microsoft.Xna.Framework.Input.Keys.LeftAlt) altPressed true else if (currentPressedKeys i Microsoft.Xna.Framework.Input.Keys.D2) twoPressed true ... if (altPressed) if (equipment accessory2 ! null amp amp twoPressed) UseItem(equipment accessory2, "Accessory 2") Both ways work to a certain degree. The end result is that you're able to press alt and then a key between 1 and 5 to quick use a consumable. Normally you have skills in those slots so holding down alt makes the skills you have bound disappear and instead shows your quick use items. The problem I'm having is that no matter what I have tried, the only way it works is that you have to hold 2 then hold alt. If you hold alt first and press hold 2 it does nothing and doesn't work. I have spent 4 or 5 hours trying to figure out why it only works when you hold down 2 and then press alt. The problem with having it only work this way is if they have a skill bound to 2 then they're going to use the skill so the system is supposed to be to hold down left alt to swap the skill bar to the quick use bar. I can't figure out why both ways I've tried doing multi key input aren't working when I press alt first. EDIT ok it must be something with my keyboard because alt 1 works but 2, 3, 4, and 5 don't work. EDIT2 restarted and 2 5 work now too, was something with my keyboard apparently.
12
Can XNA Content Pipeline split one content file into several .xnb? Let's say I have an xml file which looks like this lt Weapons gt lt Weapon gt lt Name gt Pistol lt Name gt ... lt Weapon gt lt Weapon gt lt Name gt MachineGun lt Name gt ... lt Weapon gt lt Weapons gt Would it be possible to use a custom importer writer reader to create two files, Pistol.xnb and MachineGun.xnb which I can load individually with Content.Load()? While writing this I realized I could just import a Weapon list and split them up with a helper, but I'm still wondering if this is possible?
12
How to find the 3D object the camera is pointed at I'm currently developing a 3 dimensional game (the first I've ever done and it's not as hard as I thought it would be!), but I've run into a little bit of a snag. I want to find the current block the crosshairs of the camera are pointed to, and I'm not sure how exactly to do it. The only thing I can think of is starting at the view position and moving like 0.1 units until I hit a space that is occupied by a block, but I feel like that would be a little... brute force style? Is there an easier better way to find it? Here's what I have The vector3 of the camera position. An array of block positions which may or may not be filled with blocks. The block centres are at whole numbered intervals. I promise this isn't a minecraft clone. )
12
Where does my .sav file default to in XNA 4.0 when using the StorageDevice class? I am using the StorageDevice class built into XNA and am looking to delete my save file from the solution in my XNA game. I never specify where the save file is to save, and can't find the default location on MSDN documentation. I am developing this game for the pc, and never prompt the user to select a save device. Where can I find the save file so that I may delete it?
12
Xna menu navigation with controller I have a menu that you can navigate with the keyboard, but I also want it so you can navigate it with the controller thumb sticks. But my problem is that if you push down or up on the thumb sticks it will just fly through the menu. To fix problem if it was a keyboard you would just do prevKeyState.IsKeyUp(Keys.Down). So I was wondering if there anything like this for the controller thumb sticks? I'm not sure if I'm doing something wrong but it still flies through the menu. private enum GamePadStates None, GoingDown, GoingUp GamePadStates CurrentGamePad, PreviousGamePad GamePadStates.None public void Update(GameTime gameTime) keyState Keyboard.GetState() gamePadState GamePad.GetState(PlayerIndex.One) PreviousGamePad CurrentGamePad if (gamePadState.ThumbSticks.Left.Y gt 0.1) CurrentGamePad GamePadStates.GoingUp else if (gamePadState.ThumbSticks.Left.Y lt 0.1) CurrentGamePad GamePadStates.GoingDown else CurrentGamePad GamePadStates.None if (keyState.IsKeyDown(Keys.Down) amp amp prevKeyState.IsKeyUp(Keys.Down) CurrentGamePad GamePadStates.GoingDown amp amp PreviousGamePad ! GamePadStates.GoingUp) if (selected lt (buttonList.Count 1)) selected if (keyState.IsKeyDown(Keys.Up) amp amp prevKeyState.IsKeyUp(Keys.Up) CurrentGamePad GamePadStates.GoingUp amp amp PreviousGamePad ! GamePadStates.GoingDown) if (selected gt 0) selected
12
Get intersection of vector in the middle of the screen My screen resolution is 640x480 and I have two Vector2 objects located at (10,10) and (600, 320). How can I connect these two objects and extend the line to encompass the whole screens width, how can I get the Y for the intersection at the center of the width (320)?
12
Missing texture coordinates for channel 0 Fbx and XNA 4.0 I'm getting this error while trying to load a model in XNA 4.0 Error 2 The mesh "transform1", using SkinnedEffect, contains geometry that is missing texture coordinates for channel 0. The model was dxf format then I upload it to maya then I added some skeleton and some texture (viewed it on the UV) but I still get this error. this is the load function. protected override void LoadContent() Load the model. currentModel Content.Load lt Model gt ("myModel") Look up our custom skinning information. SkinningData skinningData currentModel.Tag as SkinningData if (skinningData null) throw new InvalidOperationException ("This model does not contain a SkinningData tag.") Create an animation player, and start decoding an animation clip. animationPlayer new AnimationPlayer(skinningData) AnimationClip clip skinningData.AnimationClips "Take 001" animationPlayer.StartClip(clip) this is the draw function protected override void Draw(GameTime gameTime) GraphicsDevice device graphics.GraphicsDevice device.Clear(Color.CornflowerBlue) Matrix bones animationPlayer.GetSkinTransforms() Compute camera matrices. Matrix view Matrix.CreateTranslation(0, 40, 0) x, y, z Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation)) rotate y Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) rotate x Matrix.CreateLookAt(new Vector3(0, 0, cameraDistance), new Vector3(0, 0, 0), Vector3.Up) Matrix projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1, 10000) Render the skinned mesh. foreach (ModelMesh mesh in currentModel.Meshes) foreach (SkinnedEffect effect in mesh.Effects) effect.SetBoneTransforms(bones) effect.View view effect.Projection projection effect.EnableDefaultLighting() effect.SpecularColor new Vector3(0.25f) effect.SpecularPower 16 mesh.Draw() base.Draw(gameTime) PS 1 My knowledge with Maya amp XNA is very limited cause I used to use OpenGL C for some time. 2 Also I change my Content Processor to SkinnedModelProcessor not Model XNA Framework. thanks in advance.
12
Automatically zoom out the camera to show all players I am building a game in XNA that takes place in a rectangular arena. The game is multiplayer and each player may go where they like within the arena. The camera is a perspective camera that looks directly downwards. The camera should be automatically repositioned based on the game state. Currently, the xy position is a weighted sum of the xy positions of important entities. I would like the camera's z position to be calculated from the xy coordinates so that it zooms out to the point where all important entities are visible. My current approach is to hw the greatest x distance from the camera to an important entity hh the greatest y distance from the camera to an important entity Calculate z max(hw tan(FoVx), hh tan(FoVy)) My code seems to almost work as it should, but the resulting z values are always too low by a factor of about 4. Any ideas?
12
How do I properly use String literals for loading content? I've been using verbatim string literals for some time now, and never quite thought about using a regular string literal until I started to come across them in Microsoft provided XNA samples. With that said, I'm trying to implement a new AudioManager class from the Net Rumble sample. I have two (2) issues here Question 1 In my code for my GameplayScreen screen I have a folder location written as the following, and it works fine menuButton content.Load lt SoundEffect gt ( "sfx menuButton") menuClose content.Load lt SoundEffect gt ( "sfx menuClose") If you notice, you'll see that I'm using a verbatim string, with a forward slash " ". In the AudioManager class, they use a regular string literal, but with two backslashes " ". I understand that one is used as an escape, but why are they BACK instead of FORWARD? (See below) soundList soundName game.Content.Load lt SoundEffect gt ("audio wav " soundName) Question 2 I seem to be doing everything correctly in my AudioManager class, but I'm not sure of what this line means audioFileList audioFolder.GetFiles(" .xnb") I suppose that the xnb means look for everything BUT files that end in xnb? I can't figure out what I'm doing wrong with my file locations, as the sound effects are not playing. My code is not much different from what I've linked to above. private AudioManager(Game game, DirectoryInfo audioDirectory) base(game) try audioFolder audioDirectory audioFileList audioFolder.GetFiles(" .mp3") soundList new Dictionary lt string, SoundEffect gt () for (int i 0 i lt audioFileList.Length i ) string soundName Path.GetFileNameWithoutExtension(audioFileList i .Name) soundList soundName game.Content.Load lt SoundEffect gt ( "sfx " soundName) soundList soundName .Name soundName Plays this track while the GameplayScreen is active soundtrack game.Content.Load lt Song gt ("boomer") catch (NoAudioHardwareException) silently fall back to silence
12
Is this a good way to "get rid of the sprite shakes" for my sprites that "target" other sprites? (XNA) I'm relatively new to XNA, but very proficient with C . I want to know if this is the best way to solve the sprite shaking problem. I had a sprite class that can target a place other sprite on the map and follow it. Here's my update method public override void Update(GameTime gameTime) move this rectangle closer to the target float EntitySpeed 100f this is actually a property Vector2 velocity new Vector2() if ( target.GetX() lt this.GetX()) velocity new Vector2( 1, 0) EntitySpeed if ( target.GetX() gt this.GetX()) velocity new Vector2(1, 0) EntitySpeed if ( target.GetY() lt this.GetY()) velocity new Vector2(0, 1) EntitySpeed if ( target.GetY() gt this.GetY()) velocity new Vector2(0, 1) EntitySpeed a guy on pluralsight said it's best to update velocity taking a time into consideration to account for faster slower computer speeds var movement (velocity (float)gameTime.ElapsedGameTime.TotalSeconds) position movement position is a Vector2 is the code below a good solution to get the sprite to stop shaking? if we're "close" to the target sprite, then set the position exactly Vector2 vectorDiff this. position new Vector2( target.GetX(), target.GetY()) bool xReached Math.Abs(vectorDiff.X) lt Math.Abs(movement.X) bool yReached Math.Abs(vectorDiff.Y) lt Math.Abs(movement.Y) if (xReached) position.X target.GetX() if (yReached) position.Y target.GetY()
12
how to create texture for modelmesh? Is there a possibiltiy to create a texture from a meshpart in xna. By getting a flat version of the mesh. So I can create a texture for it and edit that texture(via rendertarget)? I need to get the texture(wich is not yet a texture) so I can put another texture on it. I can create a texture and put it on a certain mesh. But I just cant figure out how I can create a texture with the right size. I also already found out i can use text2dproj in hlsl. But when i do this i get a gray stripe in the look. Is there a better solution?
12
Does using the XNA Content Pipline eliminate the overhead caused by file IO when working with a large number of files? I'm working on a game in XNA with my goal being that it is fairly data driven so that I can easily tweak the system without having to update code. The research I've done shows that using XML files combined with the content pipeline should provide me with what I need to accomplish this. That being said, being a developer that really has only been exposed to object oriented programming I have this "one class per file" mindset that I really like because it makes finding and updating what I want to change very easy. This leads me down a path of wanting to set up a system where instead of a large, heavily nested XML file that defines everything (like the web.config files I am used to), I want to go with a folder structure with files that define individual objects or at the very least something in between. At this point in time I'm not entirely sure how many files I could end up having but I believe it could escalate to a point where it could cause a performance problem if done wrong and if I discover a performance problem because of it, redesign and consolidation of it all could be a big enough chore that I definitely want to try my best to make the right decision up front. Usually I would see the above mentioned approach being a big performance hog because of the large amount of file IO that would have to be done when loading up the game. Based on my experience with images in the content pipeline, I am assuming that XML files are also combined into a single XNB file when compiled. From this my questions become If it is true that all XML files become a single XNB file should I still expect a notable performance loss when loading the data from these "files" or has that overhead disappeared since its all within a single XNB file? If yes I am sure there tools out there that can make managing updating a single and very large XML file more manageable which I will begin researching and am open to suggestions on.
12
How to avoid character to move when selected I've got a player Class which can walk to a certain point on the screen when left mouse is pressed if (mState.LeftButton ButtonState.Released amp amp oldMouseState.LeftButton ButtonState.Pressed) if (mState.X gt CurrentPosition.X) CurrentDirection Direction.Right else if (mState.X lt CurrentPosition.X) CurrentDirection Direction.Left CurrentDestination new Vector2(mState.X, mState.Y) CurrentState PlayerState.Moving reachedDestination false Now I have several Characters on screen. If I want to select one of them I also do a left click, which sets the character to selected. if (mState.LeftButton ButtonState.Released amp amp oldMSstate.LeftButton ButtonState.Pressed) if (player1.BoundingBox.Contains(new Point(mState.X, mState.Y))) if (!player1.Selected) player1.Selected true player2.Selected false if (player2.BoundingBox.Contains(new Point(mState.X, mState.Y))) if (!player2.Selected) player2.Selected true player1.Selected false The problem is that as soon as one of the characters is selected it also performs the moving animation. This is beacuse for the trigger is the same for both moving to destination and selecting. Do you know any way to avoid this behaviour and still keep using the left click for both? Thanks in advance!
12
Speed up content loading I am using WinForms Sample downloaded from microsoft website. The problem is, that the model loading time is quite long, using contentBuilder.Add(ModelPath, ModelName, null, "ModelProcessor") contentManager.Load lt Model gt (ModelName) even a simple model, such as a cube with no textures, takes 4 seconds to load. Now, I am no expert on this, but is there anyway to decrease loading time? EDIT I've gone thru the code and found out that calling contentBuilder.Build() ,which comes right after contentBuilder.Add() method takes up most of the time.
12
Shadows shimmer when camera moves I've implemented shadow maps in my simple block engine as an exercise. I'm using one directional light and using the view volume to create the shadow matrices. I'm experiencing some problems with the shadows shimmering when the camera moves and I'd like to know if it's an issue with my implementation or just an issue with basic naive shadow mapping itself. Here's a video http www.youtube.com watch?v vyprATt5BBg amp feature youtu.be Here's the code I use to create the shadow matrices. The commented out code is my original attempt to perfectly fit the view frustum. You can also see my attempt to try clamping movement to texels in the shadow map which didn't seem to make any difference. Then I tried using a bounding sphere instead, also to no apparent effect. public void CreateViewProjectionTransformsToFit(Camera camera, out Matrix viewTransform, out Matrix projectionTransform, out Vector3 position) BoundingSphere cameraViewFrustumBoundingSphere BoundingSphere.CreateFromFrustum(camera.ViewFrustum) float lightNearPlaneDistance 1.0f Vector3 lookAt cameraViewFrustumBoundingSphere.Center float distanceFromLookAt cameraViewFrustumBoundingSphere.Radius lightNearPlaneDistance Vector3 directionFromLookAt Direction distanceFromLookAt position lookAt directionFromLookAt viewTransform Matrix.CreateLookAt(position, lookAt, Vector3.Up) float lightFarPlaneDistance distanceFromLookAt cameraViewFrustumBoundingSphere.Radius float diameter cameraViewFrustumBoundingSphere.Radius 2.0f Matrix.CreateOrthographic(diameter, diameter, lightNearPlaneDistance, lightFarPlaneDistance, out projectionTransform) Vector3 cameraViewFrustumCentroid camera.ViewFrustum.GetCentroid() position cameraViewFrustumCentroid (Direction (camera.FarPlaneDistance camera.NearPlaneDistance)) viewTransform Matrix.CreateLookAt(position, cameraViewFrustumCentroid, Up) Vector3 cameraViewFrustumCornersWS camera.ViewFrustum.GetCorners() Vector3 cameraViewFrustumCornersLS new Vector3 8 Vector3.Transform(cameraViewFrustumCornersWS, ref viewTransform, cameraViewFrustumCornersLS) Vector3 min cameraViewFrustumCornersLS 0 Vector3 max cameraViewFrustumCornersLS 0 for (int i 1 i lt 8 i ) min Vector3.Min(min, cameraViewFrustumCornersLS i ) max Vector3.Max(max, cameraViewFrustumCornersLS i ) Clamp to nearest texel float texelSize 1.0f Renderer.ShadowMapSize min.X min.X texelSize min.Y min.Y texelSize min.Z min.Z texelSize max.X max.X texelSize max.Y max.Y texelSize max.Z max.Z texelSize We just use an orthographic projection matrix. The sun is so far away that it's rays are essentially parallel. Matrix.CreateOrthographicOffCenter(min.X, max.X, min.Y, max.Y, max.Z, min.Z, out projectionTransform) And here's the relevant part of the shader if (CastShadows) float4 positionLightCS mul(float4(position, 1.0f), LightViewProj) float2 texCoord clipSpaceToScreen(positionLightCS) 0.5f ShadowMapSize float shadowMapDepth tex2D(ShadowMapSampler, texCoord).r float distanceToLight length(LightPosition position) float bias 0.2f if (shadowMapDepth lt (distanceToLight bias)) return float4(0.0f, 0.0f, 0.0f, 0.0f) The shimmer is slightly better if I drastically reduce the view volume but I think that's mostly just because the texels become smaller and it's harder to notice them flickering back and forth. I'd appreciate any insight, I'd very much like to understand what's going on before I try other techniques.
12
2D platformer multiple rectangle collision cause jitter I posted this question two weeks ago 2D platformer corner collision and I implemented NoobsArePeople2's solution. Problem is, when player intersects two rectangles that are inside each other, he starts jittering. I don't know how to describe it so I made a video http www.youtube.com watch?v 2AYUGeuxM0c In the first 4 or so seconds, you can see that when he collides with two rectangles that arent in each other or touching each other, everything works fine, but in the rest of the video, you can see that when player touches side, he starts to jitter (please note that because of fraps, my game was running at quarter of FPS I normaly have, so without fraps the jitter is much faster) To give you idea how my collision rectangles look now, here is debug mode (each rectangle is randomly colored) I have couple of algortihms in place that merge rectangles into one (still need to do some work on that), but some simply cannot be merged. One example is the C object on the right. Right now it is made of 7 rectangles (will be 3 after I complete my algorithm) and when player slides on side of it, he starts to jitter. I suspect problem is in my gravity, but Im not sure. I've spent 5 days on trying to fix this and Im lost. Heres my code (slighty modified from platformer sample) for (int i 0 i lt playerCollisionRectangles.Count i ) Vector2 depth Collision.GetIntersectionDepth(player.PlayerRectangleInWorld, playerCollisionRectangles i ) if (depth ! Vector2.Zero) float absDepthX Math.Abs(depth.X) float absDepthY Math.Abs(depth.Y) Resolve the collision along the shallow axis. if (absDepthY lt absDepthX) Resolve the collision along the Y axis. player.PlayerPositionY Convert.ToInt32(depth.Y) else Resolve the collision along the X axis. player.PlayerPositionX Convert.ToInt32(depth.X) And here is my gravity code (very very simple) if (Gravity) for camera position.Y 2 position in world playerPositionY 2 And lastly here is one of my methods to move player (i have similiar methods to move him left and up) public void MoveRight() animate.Enabled true animate.Row 0 position.X speed playerPositionX speed
12
What are the practical limitations of using XNA? Since development on XNA has long since stopped, it is unlikely that it will ever be updated to be in line with modern graphics technology, however aside from the obvious fact that it's Windows only what are the practical limitations of using XNA? The obvious ones are It uses DirectX 9.0 which means no compute or geometry shaders. It's Windows only (Excluding Monogame FNA) It requires the installation of .NET and XNA on a client's computer. 2 and 3 are obvious limitations, but can be considered acceptable. 1 on the other hand, is a bit more complicated. In practical terms what does being limited to DirectX 9.0 mean in terms of game development and graphical capability? No geometry or compute shaders means having to do more heavy lifting on the CPU, but is there any other limitations that an end user would notice? Ideally beyond a generic term such as "graphical fidelity".