How to add collision detection in a 2D car game in XNA? - xna-4.0

Right, I'm making a 2d car racing game. So far I've got the car moving etc (with a little help of course) and was wondering how do I go about adding collision detection in XNA. I've taken a bumper part (from the whole track), and made it as a separate .png file. And I was thinking of adding a collision detection box around it (so if 'car' hits 'bumper' move back by so and so). How do I add collison detection to the bumper, and integrate it with the car? Thank you!

Try this tutorial: http://create.msdn.com/en-US/education/catalog/tutorial/collision_2d_perpixel
Source code for the tutorial is in Downloads, under the two (ugly) blue boxes.

It seems this would be a lot easier if the cars were always straight--not rotated. If they were rotated you wouldn't be able to use rectangles to help.
If you do, then you could instead have the bumper included in car.png.
Then you could use the coordinates of the car and add certain values to get the length and width of the region for the bumper.
You can then do
Rectangle bumperBoundingBox = new Rectangle
(
(int)X_COORDINATE_OF_CAR,
(int)Y_COORDINATE_OF_CAR,
(int)X_COORDINATE_OF_CAR + WIDTH_OF_BUMPER,
(int)Y_COORDINATE_OF_CAR + HEIGHT_OF_BUMPER
);
Rectangle otherCarBoundingBox = new Rectangle( \* x, y, ... *\ );
bool carIsTouchingBumper = otherCarBoundingBox.Intersects(bumperBoundingBox);
This may not be perfectly perfect, as in the parameters for rectangle might be in a different order or something like that. But once you have it, you can use carIsTouchingBumper and do stuff.
If you want the bumper to be a separate image, you could do the same thing as above, except use the coordinates of the bumper instead. Also you would have to make the bumper follow the car.

Related

Organic shape that fills up space with Paper.js

I'm aware my question is maybe somewhat lazy. But I hope someone could maybe give me head start with my idea, or can provide me with an existing code example that points me in the right direction.
I want to create an organic shape/blob that more or less fills up existing space, but wraps around typographical elements. Whenever these elements move around, the shape should adjust itself accordingly. I was looking at Paper.js where examples like http://paperjs.org/examples/candy-crash/ and http://paperjs.org/examples/voronoi/ make it seem like this should be possible.
You can use the path.subtract() boolean operation, along with the path.smooth() function to smooth your shape with the type of smoothing of your choice.
Here is a demo sketch. You can also try to smooth the rectangles ; and maybe randomly add points on your curves or randomly displace all segment handles.

How to Fit the Physics Body Size of an SKSpriteNode to its Image in Xcode Using SpriteKit

So I'm not sure if this is possible, but I am trying to adapt the physics body to go with my image. Many people have told me that the hitbox for the character in my game on the iOS App Store (StreakDash - go download it!) does not work well, since it makes the game a lot harder (the hitbox hits an obstacle even though the character doesn't appear to even be touching it). This is due to the fact that the hitboxes are rectangular, whereas my character has a strange shape. Are there any ways to go around this? I thought of some ways that didn't completely work (e.g. trying to change the actual frame/canvas shape from rectangular to something else, trying to change the hitbox shape/size, trying to alter the image, etc.). It would be great if I could have advice on whether or not I should even change the hitbox in the first place (is it the type of rage-inducing game that makes people want to keep playing or stop?). But finding a way to solve the problem would be best!
Here is a picture of my character with its hitbox:
Here is just some basic code of with the SKSpriteNode and physics body:
sprite = [SKSpriteNode spriteNodeWithImageNamed:#"stick"];
sprite.size = CGSizeMake(self.frame.size.width/6.31, self.frame.size.height/3.2);
sprite.physicsBody =[SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake (sprite.size.width, sprite.size.height)];
sprite.position = CGPointMake(self.frame.size.width/5.7, self.frame.size.height/2.9);
sprite.physicsBody.categoryBitMask = personCategory;
sprite.physicsBody.contactTestBitMask = lineCategory;
sprite.physicsBody.dynamic = NO;
sprite.physicsBody.collisionBitMask = 0;
sprite.physicsBody.usesPreciseCollisionDetection = YES;
I suggest to represent the physic body with a polygon shape. You have two ways to improve bodyWithRectangleOfSize:
The Lazy way is to use bodyWithTexture:size: which will create a physics body from the contents of a texture. But as Apple suggested, the more complex your physic body is , the more work to be properly simulated. You may want to make a tradeoff between precision and performance.
The more proper way is to represent the bounding of your sprite with a convex polygon shape. See bodyWithPolygonFromPath:. There are some tools online to generate the path code in user interface. Here is the one: SKPhysicsBody Path Generator (be careful with the offset and anchor point). If you know the way to generate CGMutablePathRef code yourself, it will be easier to fit your situation.

having trouble setting up simple rectangular collisions in chipmunk

Recently I've been trying to create something I've always wanted, but never had the skill and time to do - a computer game. To be more precise, a homage / clone of one of many of my favourite games. To start with something simple I've decided to create a classic 2D platform based on the Castlevania series.
Being a Ruby programmer I've decided to use Gosu. Then I decided I don't want to reinvent the wheel so I'm going to use Chipmunk.
After a few days, I've ended up having inexplicable collision detection problems. I've added boundary-box drawing functions just to see what the hell is going on.
As you can see, Belmont collides with blocks of walls he's not remotely close to touching. Since the demo game included with gosu gem works fine, there must be something wrong I'm doing, I probably don't really udnerstand how a polygon Shape is defined and added to the space. I'm pretty sure it's not really where I draw it.
There's a public repo with the game, so you can see how walls (Brush < Entity) and player (Player < Entity) are defined and that they indeed have a simple, rectangular polygon shape. Walls are not added to the space (they are rogue), only the player is. I've tried debugging the game and see where the body position is, but all looked fine.
https://github.com/ellmo/castellvania
Player falls down slowly, but you can control him with up / left / right arrows. Tilde button (~) shows the boudning boxes and the collision boxes are supposed to be always visible.
I need some help trying to understand what am I doing wrong.
I probably don't really udnerstand how a polygon Shape is defined and added to the space. I'm pretty sure it's not really where I draw it.
That's it. Shape coordinates are added to the body position, not substracted from it.
In your Entity.boundaries replace the line
verts << CP::Vec2.new(#shape.body.p.x - #shape[vert].x, #shape.body.p.y - #shape[vert].y)
with
verts << CP::Vec2.new(#shape.body.p.x + #shape[vert].x, #shape.body.p.y + #shape[vert].y)
and you will get correct picture. (drawing will be still broken, but bounding boxes will be correct.

Best approach for "game" problematic

I have to tell you, I'm completely NEW to XNA, and I know NOTHING about vertex, multisampling, etc etc..
However, I love so much programming and windows phone that I wanted to start an immense challenge... create a XNA game! :D
ok, let's stop the story and start explaining..
I'm making a big game... which I've worked for it for almost 1 month, now it's almost over..
I've just a big issue, which is the central point of the game... think about it as a 1024x800 puzzle, each point of puzzle can be clicked, and when it's clicked it must change color..
so we have 2 hard point to do,
1) UNDERSTAND WHICH PIECE I'VE CLICKED
2) COLOR THIS PIECE
I thought about 2 approaches
FIRST APPROACH
1 PNG big puzzle background 1024x800
N PNG for each puzzle piece, with transparent layer around the piece ( each piece is 1024x800, in the correct position )
by merging the N+1 PNGS we have the complete puzzle, now, it's REALLY easy to understand which piece I've clicked, because I just have to cycle the N textures, and when I got the one which havent the transparent pixel in the point clicked, I've the piece!
then, for color it, I've just to color the texture in the draw part.
it's easy, the problem is that if I have to drag, zoom, 50*4 pngs, it's really slow :(
SECOND APPROACH
1 PNG big puzzle 1024x800 with all pieces merged, EACH piece will have a different color fill, example, 1) 250,250,250 2) 245,245,245 etc
After the PNG has been loaded, I calculate the pixel indexes by using GetData for each piece and store it in an array for each piece
for getting the piece selected, it's easy.. I've just to calculate the y*width+x and get the piece with that value on the array.
problem is that when I've to color.. I've to iterate the array and change the RGB and then finally do a SetData.. it takes 1 second to colorate that piece.. it MAY be acceptable.. but I want better ...
second approach is way MUCH MUCH MUCH faster when dragging and zooming, because it's only 1 PNG, and I can use bigger resolutions thanks to this, this far way best approach
any suggestions??
Thanks,
Luca
So you have a 1024x800 puzzle, with each pixel being a piece? You are not going to want to make 819200 image files or define 819200 individual behaviors for each pixel.
You need to (well, should) use object-oriented concepts for this. Here is a basic idea of the path I think you should take:
Define a "Piece" class. This Piece represents a game piece.
In the Piece class, define a rectangle which represents this piece on the board. If your piece is an irregular shape (like an S tetronimo, etc), define multiple rectangles. If you have multiple different types of pieces (and different shapes), you will want to use inheritance and make each different type of piece inherit from the Piece class, but define its own rectangles. However, if your 'pieces' are just pixels on the screen, just make a 1x1 Rectangle.
Fill the rectangles with a color using SpriteBatch. You can use a single white pixel png and stretch it to fill the rectangle(s) as well as specify the color.
Use the rectangles to hit-test your pieces with touch. If a touch falls within your rectangle, you have selected that piece. If your pieces are only 1 pixel in size, it's even easier: simply lookup the piece at the touch position's X and Y values.
Now for the game board: depending on the shape and possible positions of the pieces, you will need to select a way to store them. If all your pieces were squares, you could store them in a 2D array. Otherwise you might use a map, where the key is the piece's position and the value is the piece itself.
A basic summary of this approach: don't try to store your board in a single texture. Writing/reading texture data is slow and textures are not made to act as data structures. Instead, store your pieces as individual objects. Iterate through each piece and draw it to the screen.

Algorithm for positioning rectangular and randomly sized objects inside a non-rectangular canvas

. . Hi there, everybody.
. . I have a canvas defined by many points (x,y)--it's not rectangular, but at least it will follow some almost-hexagonal shape (like a distorted hexagon, with angles that are always < 180 degrees). I also have a big collection of different rectangles (more or less 140 of them, with different widths and heights) and I need to position them inside the shape. They must be positioned as if they were being pushed by gravity (I mean... the top of the shape doesn't needs to be filled, but the bottom needs).
. . Right now my only idea is to store the min and max "x" position for every "y" position (something like: limits[300] = [30,30]; limits[299] = [29, 32]; ...), loop through the rectangles, get their area and then compare the values to find the best position. The biggest issued I have right now is that they need to be organized in a "organic" way, not like a table (I can't have rows and columns and position them inside cells. they need to be positioned as good as they can be, like fluidly, side by side, one above other...). I'm not sure how to manage the positioning.
. . I know some good examples of "auto-balanced" objects (a good one is the "Ball Pool" Chrome Experiment: http://mrdoob.com/projects/chromeexperiments/ball_pool/), but they use rectangular canvas and circular objects, which are much easier to compare the limits.
. . Right now my best idea is to check the objects for every possible x/y combination, from bottom to up, from left to right, checking if any area would overlap, but this would probably lock the whole computer for the calculations for minutes (the more itens on the screen, the more calculations would be needed).
. . The project is running on Flash, but any example, tip, algorithm, paper or pseudo-code will be of great help.
I think you can get all done using a physics simulation. It might sound complicated, but it's not as hard as it sounds. There are several physics APIs for actionscript 3. I've used the as3 port of Box2D and I'm pretty happy with the results.
The way I would go about it is:
define shapes for the walls ( the lines that make your polygonal shape )
define the boxes(rectangles)
create the physics bodies with the proper display objects information(linkage id , etc. )
add them to the physics world and simulate.
I don't know what your experience with actionscript 3 is, but have a look at the World Construction Kit. It should allow you to get on track fast.

Resources