Camera Thread

Topics: User Forum
Mar 17, 2009 at 10:59 PM
Edited Apr 9, 2010 at 7:42 AM

All right anyone here looking for stuff on 2D cameras look no further. Contained within is a class that offers a simple/powerful camera. Any questions about this please post here (sorry genbox but i think 1 off topic thread is better than a whole off-topic conversation in someones question thread!).

InputHelper link, Camera2D link

Update 3/21/2009: updated the code to use an InputHelper class and added smooth camera resetting

Update early 3/22/2009: updated the Camera2D class to have smooth movement/zoom/rotation (might have to play around with the zoom/rotation/newly added move rate to get things to look nice)

Update 4/12/2009: added the ShouldDraw method. needs 2 new usings so check at  the top for the new using list.

Update 6/1/2009: added lambdas (yay!) that control the update to a great degree, documented everything, and generally cleaned stuff up.

Update 6/5/2009: heavily revised the InputHelper class to offer mouse and keyboard support as well as renamed variables

Update 9:21:2009: added syntax highlighting to the code. A change to how the properties are set on the Camera2D may also have slipped in at some point.


It needs a little explanation:

After constructing the camera2d, just change any properties that you need changed (all variables have defaults). Since the method of use for bodies varies so much, you must develop your own method to determine your own tracking body. If you need to change some aspect of the controls, redefine the appropriate Func property. Anyone can use this if they like, i dont really care. Just please dont claim the work as your own.
Use guide:
first copy and paste the InputHelper and Camera2D code to separate class files, putting them in your namespace. Then add
Camera2D camera;
InputHelper input;
into your game screen file, main game code, whatever.
Then add
camera = newCamera2D([all parameters have descriptions]); (note that all of thses parameters are optional except the camera size)

input = new InputHelper();

then go to your update method and add

input.Update();
camera.Update(input);
then in all of your draw methods when calling spriteBatch.Begin use the camera.CameraMatrix as an argument (along with the other arguments neccesary). That should get you up and running with the camera!

Mar 17, 2009 at 11:05 PM
ALRIGHT much better haha
anyway i am still interested in the same questions, if you hadent read them i asked
1. How do i center the tracking body on the screen
2. How do i change the zoom speed, the default seems to be 0.1f but when i input it instead of null it goes much faster.
3. i cant remember, sorry haha, i hope you read it in the other thread
Mar 17, 2009 at 11:07 PM
To answer your questions TLegion,
1. *Please* set that to the size of the screen or the zooming won't work right
2. If you set camera.TrackingBody to the body you want to track, the code in the update method will automatically handle the tracking for you.
3. The default zoom rate is 0.01f because games update so fast, they get that applied tens, if not hundreds of times per second. If you want it to zoom at a reasonable but fast rate, try 0.02 (or 0.03)!
Mar 17, 2009 at 11:17 PM
Edited Mar 17, 2009 at 11:39 PM
thanks man that makes sense
by the way im going to implement a speed to the camera, or attempt
this will add a bit of elasticity like i had on the old camera, im not sure how matrices work but im deinfatlye gonna try

edit: i finished and the elasticity effect looks great, thanks for all your help on this and in general
Mar 18, 2009 at 12:16 AM
You're welcome, this is one of the things that im gonna add into my game framework (and convert to other languages if i need to) so that i dont have to rewrite it everytime i need it.
Mar 25, 2009 at 6:34 PM
You dont have to change anything to disable bodies, the way this class works does not change the way farseer is used, you can use it like you normaly would.
And they way I have it check if something is on screen,
is i made my own method.
I defined a rectangle in the camera class that was equal to the camera size and position,
then i made a method called isVisible
it went like this

public bool IsVisible(Rectangle Rect)
{
CameraRect = new Rectangle(position.x, position.y, graphics.preferredbackbufferwidth, graphics.prefferedbackbufferheight)

if(cameraRect.intersects(Rect))
return True;
}

then in your draw method in your sprites class or wherever

public void Draw(Camera2D camera)
{
SpriteRect = new Rectangle(X, Y, Height, Width);
if(camera.IsVisible(SpriteRect))
{
spritebatch.draw(image, position, color.white);
}

Spritebatch.Begin(blah)
Sprite.Draw(spriteBatch, FollowCamera)

It works very well for me, hopefully thats clear enough, thats the rough idea.

If anyone has a better way to do this please tell me as this is the only way i know
Mar 25, 2009 at 7:10 PM
I realize this, then you could just add the rectangle updates in your movement code if you really thought it mattered that much,
it doesnt make much of a difference to me as it doesnt change my performance at all plus its the only wya i know how.
Im sure there are better ways though
Mar 26, 2009 at 1:01 AM
Thanks for the compliment! To answer your question, i'm planning on adding an AABB to the camera (rectangles use ints and thus are imprecise) so that i can do texture drawing checks. Unfortunately the code for checking if a texture should be drawn is also a very game specific set of code and won't come with this class.
Apr 7, 2009 at 7:25 PM
Edited Apr 7, 2009 at 7:26 PM
Hey man are you going to implement the aabb draw check soon?

If not, then I will create a crappy version and if it somehow works ill post here
Apr 8, 2009 at 1:32 AM
Edited Apr 8, 2009 at 1:34 AM
Ooh sorry forgot all about that... ill get on it like in a couple hours (working through a kinda hairy problem with my game code right now). I've been thinking and what ill do is provide a method to check if a texture that sits at a given position is intersecting with the camera as well as the AABB for any other use you might want...
Apr 8, 2009 at 5:00 AM
Its alright do it whenever you feel ready,
I dont wanna interupt anything your working on right now,
the method is not even neccessary right now I'm just setting up all the game mechanics and things right now so its alright.
Apr 8, 2009 at 5:13 AM
Yup... I already have most of my game mechanics down (aside from a few details) so i hope to get on this soon (i want large levels and that might slow the game way down without this).
Apr 8, 2009 at 5:26 AM
Edited Apr 8, 2009 at 5:39 AM
I will be in the same situation so it will be helpful in the future,
I still have no idea how to go about creating maps or serializing stuff,
but I am going to test certain techniques(create map, divide up, find the vertices in Inkscape, make a polygon body and subdivide the edges and pray),
and serialization will be extremely easy when xna 3.1 rolls out in May(cant wait)
Apr 8, 2009 at 7:03 AM
Edited Apr 8, 2009 at 7:09 AM
Me too. I figure i'll roll a custom content importer/exporter (i use simple things like circles/rectangles for terrain) that sotres position and size data for the terrain components. Unfortunately i havent gotten to this point yet but when i do ill probably be posting another demo.
Apr 12, 2009 at 12:02 PM
Edited Apr 12, 2009 at 12:04 PM
There ya go added the AABB texture check... Please test it to see if it's broken.... On a side note, i plan to disable smooth movement (or at least tone it down a lot) when tracking a body because it feels too "soft" and not right.
Apr 12, 2009 at 4:32 PM
Not to sound ungrateful
But where is it?
Im looking for where you added the code and i cant find it,
i checked the original post and every other post and i dont see what your talking about.
And what do you men by smooth? Smooth zooming or smooth following?
Apr 13, 2009 at 12:05 AM
Edited Apr 13, 2009 at 12:09 AM
*scratches head* i was SURE i added that code... Oh well lemme add it again. With the tracking: i mean smooth following... its irritating to see the camera bounce up and down the way it does when following a bouncing circle. Edit: its the ShouldDraw method and 2 new usings.
Apr 13, 2009 at 7:48 AM
haha found it this time,
and if you are looking for a sortof interpolation effect i have added that to the camera class,
of course i am trying to figure out if you dont want that or want that.
Apr 13, 2009 at 8:48 AM
"interpolation effect"? what do you mean?
Apr 13, 2009 at 9:54 AM
Edited Apr 13, 2009 at 9:56 AM
Interpolation,
like in animation where it smoothes a path to the final spot instead of just jumping there,
or vetor2.lerp which will smoothly update the position instead of having to jump by increments.
I have added an interpolation for its hcange in position

edit:
Imagine a non interpolated camera,
its like its got a stick attatched to the body,
and an interpolated one has a spring,
I added a parameter to the camera class which changes how fast the camera will move to keep up with the bodies position.
Apr 13, 2009 at 12:19 PM
Edited Apr 13, 2009 at 12:21 PM
If you mean a separate speed for when bodies are being tracked, i would love to see the changes you made to get that working, otherwise i added that a while ago. I'm also thinking that i'll switch the camera to being able to track multiple bodies (by swapping out the tracking body variable with a list of bodies variable that it tracks).
Apr 13, 2009 at 5:15 PM
Edited Apr 13, 2009 at 5:17 PM
tracking multiple bodies would be great,
ive been thinking about ways to have dynamic camera movement,
i was thinking of doing the should draw checks to tell it to zoom out or in dependent on a reference geom.
You could place it at the bottom of the screen and when the play jumped it would zoom out.
Not very interesting but its something,
But youve got me confused on what you are asking about the speed.
I am not home at the moment but i will just post the code when i get back, its a simple tweak.
What i did was gave the camera a movement speed(specified in the constructor), then for the updating of movement i performed a Vector2.Lerp(interpolation) to the tracking bodies position(i change a piece of your code when you first releaased this class)
which would move at the specified speed.
Jeez i didnt think this would be so hard to explain,
if we were to talk with a visual example again,
setting the speed high would let it keep up with the tracking body in almost all circumstances.
Setting it low would make it fell like the camera had a bit of give.
For the bouncing ball example setting the speed high would produce a curve like this
/\/\/\/\/\/\/\/\/\/\/\/\/\ very rigid with no transition or smoothing
a low speed would produce a more natural motion
*i cant draw a good curve with letters or symbols like i did above but it be like
UUUUUUUUU or something along those lines : D
Apr 14, 2009 at 1:48 AM
Yeah, my problem though is how to calculate zoom so that it actuallly lets you see everything on the list. If you notice, around  march 22 i added smooth movemetn, you might want to make sure you have all the latest code. Thanks for the offer though.

Apr 14, 2009 at 4:03 AM
Yeah ive just been reusing the first version so I may be a bit out of it haha,
I havent had to implement the camera for a while but now i will for my map editor(im making progress)
and im going to start work on a solid enemy class.
If you could give me any help on serialization that be great.
For some F*CKIN reason VStudio wont allow me to say
StorageDevice.BeginShowStorageDevice (whatever its called)
Thats the only part I am unable to do but for the love of god i cant figure out why
I have the using statement and xna framework in the references obviously.
This is pissing me off so god damn much.
Sorry for getting off topic but it is whats stopping me from finishing my map editor,
however sloppy or inefficient it may turn out to be, I think its a really interesting way to do it,
and it will allow so much flexibilty in placing sensors and collision geoms.
Apr 14, 2009 at 4:56 AM
Edited Apr 14, 2009 at 5:06 AM
Unfortunately i don't plan to work on the xbox until i actually finish my game (convert, fix any obvious errors, and pray) so i dont have a solution for that. Sorry, i wish i could help! Edit: after poking around in help some, i found the Guide.BeginShowStorageDeviceSelector method, and its use would be something like this:
IAsyncResult result = Guide.BeginShowStorageDeviceSelector([whatever the params are]);
...
while (result == null) {}; // i think this is the way to wait for it
//use result
Now, i havent actually used this, but im pretty sure that that will work.
Apr 14, 2009 at 6:41 PM
No for the pc, i need help with pc serialization(getting the storage device)
I am not worried about the xbox for now
Apr 15, 2009 at 12:41 AM
If you have a level object, try attaching the [Serializable] tag to it (the class), and if that works do something like this:
LevelObject o = [get the level object]
IFormatter formatter = new BinaryFormatter();
//you'll have to play around with the flags and stuff for this
Stream stream = new FileStream("MyLevel.lev", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, o);
stream.Close();
Remember: Help is your friend! (i found all of this from a 5 minute search of help, but then i knew what to look for, often searches can take a looooong time if i dont)
Apr 15, 2009 at 12:44 AM
Edited Apr 15, 2009 at 2:17 AM
Well ive searched xml for hours hundreds of times and the tutorials are either from 2006 or end up not working
Why not use xml serializer? what does iformatter output it as? WOuld i load it in the same way?
And where does it save it to? If you dont declare a storagecontainer or storage device where does it go?

edit:
It seems i can get the xbox's storage device but i cant get a pc's... lame
But since my editor will be in debugging and not the release binarry should be fine,
and if i need to do some saving debugging on the computer i can do a #if XBOX test to decide which type to use.
Apr 15, 2009 at 5:53 AM
ALright i got it to serialize and deserialize my information,
cool
But when i try to deserialize it in another project is says it cant find the right assemble, or it says it cant find the right importer(if i add it to the content folder)
Do i have to have it in the same solution as my game?
Im confused and tired and am going to sleep : (
Apr 15, 2009 at 6:39 AM
I do not entirely understand how to use the ShouldDraw method. I am not exactly sure what I am supposed to put for origin. When I use PolygonOrigin which is from the Texture to Vertices guides, nothing from my physics categories shows on my screen.
            // Draw Texture to Vertex Object
            if ( camera.ShouldDraw(sprite,body.Position,polygonOrigin,body.Rotation))
            {
                spriteBatch.Draw(sprite, body.Position, null, Color.White,
                                           body.Rotation, polygonOrigin, 1, SpriteEffects.None, 0);
            }

If I put !camera.ShouldDraw(...), it works, but I am not sure if that is correct, or just drawing everything even if it shouldn't. Also, concerning non-farseer physics objects such as scrolling clouds, I would like to know how I should use this method. Again, I am not sure what I should put for origin, and since there is no rotation, do I just put 0f for that? When I made origin and postion Vecotr2(0,0), the texture drew itself when the sprite increased as it got higher, and therefore closer to the cloud but dissappeared when my sprite body was lower and it should still be showing.Thanks for your help and the camera!
Apr 15, 2009 at 7:56 AM
I have yet to use this check yet but!
it seems its check if the origin goes offscreen so you will see part of it randomly dissapear,
I thought this was going to be an AABB checker though?
Apr 15, 2009 at 8:30 AM
Ok what you do is feed in a texture, the position at which the textures center resides, and the textures origin (which is a vector2 with the x and y components set to half the textures width and height respectively). The method will work with any texture (its not specific to farseer). @TLegion: It does! i just havent actually tested it so there is likely to be some errors (but i hope to test it soon). What it does is, depending on the rotation of the body, calculate the min and max position of an aabb (same for the camera) and then checks if they are intersecting.
Apr 19, 2009 at 4:33 AM
Ok, it seems to work basically, but sometimes textures do disappear even though they are not off camera. I have a boat on a "wave" which is just a curved texture and if the boat jumps up off a wave too far, the whole wave disappears. The wave is a vdery long texture though and extends beyond the range of the camera in both directions if that makes a difference. It works pretty well for the most part and my game is running far smoother now that it is not drawing everything away form the camera.  I don't think that will be a problem for my project grade though. Less than two weeks left! I wish to continue work on the game after that though.
Apr 19, 2009 at 4:36 AM
Yeah. i gotta figue out how to calculate an actual intersection (the current method i use to check textures is a bit hacky), perhaps i'll change it to use the Rectangle class.
Apr 19, 2009 at 9:07 PM
I got your email kaiseer and i looked over the code you sent, and it looks good. However, in order to get the camera to work, you need to change all of your calls SpriteBatch.Begin to use the camera's Matrix as the fourth argument (the other values are up to you). This will cause all sprites you draw to be scaled, rotated, and translated so that they appear on screen properly.
Apr 27, 2009 at 6:12 PM
Hi there. I'm afraid to ask this, because it's a really silly question, but as I'm really new to XNA here it goes:

How do I use this class? :$
Should I create a Camera2D instance in the main screen class, and the update it in the Update method? I've tried that, but doesn't work. Sorry for the dumb question :S
Apr 27, 2009 at 7:49 PM
Edited Apr 27, 2009 at 7:52 PM
make a class with the 2d camera code posted above
(you can just copy and paste, just make sure to change the namespace)
then you make an input handler class
(again the code is above, id rather not have to do this class but its part of the update, ypu can mod the update to not use it but whatever)
Then in whatever class you are going to put it in(game1.cs mostlikely)
Add
_2Dcamera WorldCam;

then initialize or load its content

WorldCam = new _2dCamera(set these parameters, remember you can just null the stuff you dont wanna change or arent sure of)

then you set the tracking body

WorldCam.TrackingBody = Player.Body;

then you call its update method and add a new input helper.

WorldCam.Update(new inputHelper());

then you apply its matrix to the draw stuff.

spriteBatch.Begin(spriteblendmode.alphablend, sortingmode.deferred, savestatemode.none, WorldCam.CameraMatrix);

//Draw whatever you like, do it like you normaly would, you should draw the tracking body though, so draw your player
spritebatch.Draw();

spriteBatch.end();

Hope it goes well for you

EDIT:
I noticed you said main screen class,
if your using a screen system you can easily put it in the screen manager then initialize it in whatever gamescreen will use it, and set itis tracking body.
I would suggest making a new one in each game screen that needs a camera just because it would be easier to mange.
Things like what things draw according to the camera, and what bbody its tracking etc.
Apr 27, 2009 at 9:21 PM
Edited Apr 27, 2009 at 9:36 PM
Thanks Tlegion! Works perfectly :)
But... When I enter to the debug view, the body's frames are drawed without considering the camera (I mean, in the original position and not where the textures are (see screenshots). Is that normal?

http://img115.imageshack.us/img115/2382/dosv.jpg
http://img154.imageshack.us/img154/4905/uno.jpg

Thanks for your help!

Edit: I don't quite understand the utility of the inputhelper, I removed the code and the camera still works nice. Is only for the case when there's no tracking body? (to control the camera with the controller)
Coordinator
Apr 27, 2009 at 10:07 PM
Yes, that is "normal".

The debug view does not support matrix tranformations. I might have a look at it later and work up a version that does.
Apr 27, 2009 at 11:21 PM
The input helper is a class that is supposed to handle keyboards and gamepads,
its used in screen management systems like the one farseer uses,
The code that Rogue put into the update method changes the cameras position and such based on an xbox controller,
personally i right my own code for camera control,
anyway that is just for manipulating the camera, but its not neccesary.
Apr 27, 2009 at 11:59 PM
Thanks a lot tlegion and genbox. I love the camera so far.
Apr 28, 2009 at 2:43 AM
All right, i better put a little guide in the first post about how to use the camera. I actually don't have a problem with the debug view (i can draw it properly, with the matrix and everything). Thanks for the compliment! i currntly only use InputHelper for xbox controls because i would either have to inflate the InputHelper class to a big size or make 3 or 4 separate classes. Now if genbox is willing to include this camera in the demo apps, i can clean it up and add keyboard/mouse controls and submit it all in a patch with use instructions.
Apr 28, 2009 at 5:12 AM
Why would you need more classes?
I dont think it woud be a problem adding keyboard and mouse states to the
current input helper would be bad.
Of course i dont know to much in the ways of optimization but i dont see
any problems in terms of organization or efficiency
Well im just a young padawan i still have alot to learn
Apr 28, 2009 at 6:26 AM
Then i would have to make it a behemoth class and 3 smaller classes (1 for each input type) with a parent one that contains them would be smarter it seems.
Apr 28, 2009 at 9:20 AM
Edited Apr 28, 2009 at 9:21 AM
For controlling the game I guess I should use the same inputHelper class (I already have a class for managing the gamepad/keyboard inputs, but I guess is better avoiding having two different input managers) and extend it to my needs. Right?

BTW: Did I mentioned before that I love this camera?
Apr 28, 2009 at 7:28 PM
I disagree,
having to call KeyboardInput.CurrentKeyState is pointless
and having to initialize a keyboard class a gamepad class and a mouse class in your screen system...
it seems lie your making it harder than it needs to be.
Theres no reason you could just have one input class with each input controller,
rather than making 3 child classes you would have to call specifically for each one.
And pnikosis i would say either expand Rogues class or use your own,
it would probaly be alot easier to have one input class,
especially when you have to assign specific player indexes(havent had to yet but i can imagine mass confusion)
Apr 28, 2009 at 10:14 PM
Thanks tlegion, that's what I thought: Expanding Rogue's class instead of using another one.
Jun 2, 2009 at 7:35 AM

All right, updated the code. See the changes section for what i did. I am also thinking of expanding the InputHelper class to include keyboard and mouse support; whaddya think?

Jun 5, 2009 at 12:31 AM

Support for mouse and keyboard would be perfect.

Jun 5, 2009 at 6:41 AM

The project I'm working on requires use of a mouse, so I looked around and found out how to translate the mouse coordinates to game world coordinates. Here's the solution:

public Vector2 ToWorldLocation(Vector2 position)
        {
            return Vector2.Transform(position, Matrix.Invert(CameraMatrix));
        }

Jun 5, 2009 at 7:18 AM

 already wrote it so i'm going to post it in just a second! About that cod: interesting. Mind if i add that to the camera class?

Developer
Jun 5, 2009 at 2:24 PM

@RCIX: Be sure to make all that mouse stuff conditional so it will still work on the Xbox360.

Jun 6, 2009 at 2:34 AM

@RCIX: I don't know what a cod is you talking about the ToWorldLocation function?

Yes please include it :). It will convert a location on the viewport (mouse area) to game world coordinates (where the camera is looking at), very useful for mouse interaction.

Just copied over the new input helper class, thank you!

Jun 6, 2009 at 8:04 AM

@matt: yep did that thanks!

@daswampy: I'll get on that as soon as possible. You're welcome!

Jun 22, 2009 at 11:58 PM

Good work, this is an awesome camera class... just awesome..

I'm trying to make a parallax effect while using it and I'm running into a few issues. Has anyone managed to get parallax scrolling effect working? I think when using matricies you need to use some trig to specify the speeds that each layer will scroll however I'm not certain.

The way I tried to do it is by adding a ScrollRate property to the camera and then implement it in the Matrix.CreateTranslation(-_position.x * ScrollRate, -_position.Y, 0). Then my draw call looks like this:

 

                for (int d = 0; d <= 5; d++)
                {

                    if (d == 0)
                        camera.ScrollRate = 0.0f;
                    else if (d == 1)
                        camera.ScrollRate = 0.4f;
                    else if (d == 2)
                        camera.ScrollRate = 0.6f;
                    else if (d == 3)
                        camera.ScrollRate = 0.8f;
                    else if (d == 4)
                        camera.ScrollRate = 1.0f;
                    else if (d == 5)
                        camera.ScrollRate = 1.2f;

                    spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState, camera.CameraMatrix);

                    for (int l = 0; l <= 5; l++)
                    {
                        for (int s = 0; s < sprites.Count; ++s)
                        {
                            Sprite sprite = sprites[s];

                            if (sprite.LayerDepth == d && sprite.Layer == l)
                                sprite.Draw(spriteBatch);
                        }
                    }
                    spriteBatch.End();
                }

 

This seems to work if all the scroll rates are set at the same speed however things start to get weird when setting the scroll rates like they are above. Any help would be very appreciated!

 

Jun 23, 2009 at 3:20 AM

This is just an idea, I haven't tried it yet.. but couldn't you just render objects in other layers with different zoom amounts?

e.g.

spriteBatch.Begin(..... ,camera.Layer0Matrix);
// draw objects in layer 0
 spriteBatch.End();

spriteBatch.Begin(..... ,camera.Layer1Matrix);
// draw objects in layer 1
 spriteBatch.End();

spriteBatch.Begin(..... ,camera.Layer2Matrix);
// draw objects in layer 2
 spriteBatch.End();

 where each matrix defines a different level of zoom.

Jun 23, 2009 at 4:01 AM

Oh right... I never thought of using multiple matricies haha! I tried it out and it seems to do the job fine, thanks a lot!

It makes sense since the problem clearly came from passing several different scroll values to a single matrix.

Sep 19, 2009 at 11:57 AM

THANK YOU FOR THIS NICE CLASS :-) Work perfekt!

One Error:

Replace "input.RightStick" with "input.RightStickPosition" ^^

Sep 22, 2009 at 1:25 AM

Hm, can't find what you're talking about. If you could provide me with a line on which this error occurs i would be more than happy to fix it.

You're very welcome, i'm just glad i could help some people with this particular problem...

Dec 17, 2009 at 5:26 PM

I am new to the Farseer world.  I am trying to do a simple sprite on the screen and move it aournd.  The sprite position does not change.  I get the trackingbody is null message.

I noticed you have changed it to null as soon as the Right triger is pressed.  Any way, I can find out where the trackingbody is on the screen.

Code is:

Body planeBody;

<font size="2" color="#0000ff"><font size="2" color="#0000ff">

protected

</font></font><font size="2" color="#0000ff">

 

</font>

override void LoadContent()

planeBody = camera.TrackingBody = planeBody;

<font size="2">

camera.Position =

</font>

new Body();new Vector2(0, 0);

......

<font size="2" color="#0000ff"><font size="2" color="#0000ff">

protected

</font></font><font size="2" color="#0000ff">

 

</font>

override void Update(GameTime gameTime)

input.Update();

camera.Update(input);

_sprite.Position = camera.TrackingBody.Position;

<font size="2">

.............

</font>

protected override void Draw(GameTime gameTime)

{

<font size="2">

GraphicsDevice.Clear(

</font>

Color.CornflowerBlue);<font size="2">

 

</font>

spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.None, camera.CameraMatrix);

<font size="2">

spriteBatch.Draw(_sprite.Image,_sprite.Position,_sprite.FrameRectangle,

</font>

Color.White);

<font size="2">

 

</font>

 

Jan 13, 2010 at 7:48 PM

this looks really awesome!

I get some errors though: in the Camera2D class I get:

 'FarseerGames.FarseerPhysics.Collisions.AABB.AABB(ref Microsoft.Xna.Framework.Vector2, ref Microsoft.Xna.Framework.Vector2)' has some invalid arguments 

(the error comes from this line):

texAABB = new AABB(new Vector2(botLeft.X, topLeft.Y), new Vector2(topRight.X, botRight.Y));

it complains that the vectors arent 'ref' , but I cant just put 'ref' in front of it? How can I fix this?

can u help? Thanks!

Coordinator
Jan 13, 2010 at 7:50 PM

My guess is that you need to do this:

Vector2 first = new Vector2(botLeft.X, topLeft.Y);
Vector2 second = new Vector2(topRight.X, botRight.Y);

texAABB = new AABB(ref first, ref second);

 

Jan 13, 2010 at 8:59 PM

thanks! that solved the errors!

now to see if it works as it should.. :D

Jan 25, 2010 at 2:19 PM

First of all, thanks for the awesome class, it really saved me a whole lot of work =)

 

I'm just starting with Farseer, developing a good 'ol platforming game. I added the camera2D and inputHelper classes to my code, intialized them, made the camera track the player body aaand... the tracking is off. While the camera points the center of the screen, the player is always in te upper left corner (actually, everything is in the upper left, platforms, everything!)

The code is:

 

player.body = BodyFactory.Instance.CreateRectangleBody(sim, player.scale * player.texture.Width, player.scale * player.texture.Height, 1);
            player.geom = GeomFactory.Instance.CreateRectangleGeom(sim, player.body, player.scale * player.texture.Width, player.scale * player.texture.Height);
            player.Position = new Vector2(300, 400);
            player.geom.CollidesWith = CollisionCategory.Cat1;//CollisionCategory.All & ~CollisionCategory.Cat2;

            //player.geom.OnCollision += player.on
            player.geom.RestitutionCoefficient = 0.0f;

            

            camera.TrackingBody = player.body;

 

Maybe the there's a mix up with world positions? Any help would be greatly appreciated!

 

Jan 25, 2010 at 2:25 PM

so you're saying the camera just points at a wrong point, but it follows the target as it should?

my guess is a wrong offset then..

Check your settings for size of the window and camera position at start.. maybe the problem is situated there :)

Jan 25, 2010 at 2:43 PM

I´m not even touching the screen size, just the default window XNA creates. I'm feeding the Viewport (X,Y) from the Graphics Device to the Camera in the constructor. No idea where else should i check.

 

(sorry if the questions sound dumb, but i'm just a beginner :P)

Jan 25, 2010 at 2:47 PM

I'm not that experienced myself,

 

but I have worked with camera's already (not this one, but one of a friend of mine)

try setting the window size yourself (type
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 600;
in the initialize part of the game)

and then feeding (800,600) as the size to the camera. (this is the default size, but just to make sure :) )

Also, make sure that the camera takes on the exact same position as the trackingobject at game start.
If that position is wrong, logically all following positions are wrong.

Jan 25, 2010 at 3:06 PM

Thanks StormBoy!! works like a charm now =)

Jan 25, 2010 at 3:09 PM

No problem mate, we're here to help :)
took me quite a long time to fully understand camera's (they mostly do exactly the opposite of what you think they should do),
but now I'm quite confident with them :)

good luck with that platformer ^^

Feb 27, 2010 at 3:13 AM

Hi.
Could someone lay out a simple example of AmazingGadgets.Camera2D with the ability to control any object and track its movement, as well as any number of static objects.
I apologize in advance, I'm just learning XNA and FPE, but English is not my native language, so it is difficult to deal with the fact that described.

You can send the answer to my E-mail: adminfort@gmail.ru

I would be very grateful for the help.

Mar 26, 2010 at 3:31 PM

 

I hate to be a bother to everyone but how would you go about offsetting to where the camera needs to be with out doing spriteBatch.Begin(stuff, more stuff, even more, camera.CameraMatrix)?

I know it seems weird that I would EVER need to do something like this but its because I have a special effect that is determined by rectangles that are set up all around the map. Thing is I don't know how to tell

the rendertargets to look in these new positions to save the textures there. Right now I have this:

 

 

                spriteBatch.Draw(SceneTexture, new Rectangle(0, 0, (int)(blobs[i].Width * camera.Zoom), (int)(blobs[i].Height * camera.Zoom)),
                    new Rectangle(blobs[i].X - (int)(camera.Position.X * camera.Zoom),
                    blobs[i].Y - (int)(camera.Position.Y * camera.Zoom),
                    (int)(blobs[i].Width * camera.Zoom), (int)(blobs[i].Height * camera.Zoom)), Color.White);

It doesn't work either. I have NO clue what it honestly is doing.

In conclusion, if someone could show me how to find new Rectangle based on the camera offsets and zooms (don't need rotation) that would be

amazing. Any help on how to do this would be greatly appreciated :) 

 

Apr 9, 2010 at 7:34 AM
Edited Apr 9, 2010 at 7:45 AM

First of all, i'm ba-ack.... :)

Second, i plan to put this code on PasteBin so that you don't have to scroll past a zillion lines of code.

@sonic4305: Um, i'll need to think about that some, i'm just getting back into XNA and related stuff after a long break!

Edit: after examining your code line, it looks liek you should be removing the multiplier for position, as that is unaffected by zoom. Sizes for objects are, however.

Apr 9, 2010 at 4:08 PM

Can someone provide a sample function to have a threshold of when the camera starts to move in a specific direction?  Right now, whenever the tracking body moves, the camera moves near 1:1 with it.  How do I have the camera only move when the tracking body gets to around 3/4 screen space in X/Y direction?

Apr 21, 2010 at 6:46 AM

What you basically need to do is something like this:

 

In the Update function, there's a chunk of code that says if trackingBody == null, modify the code in the else to do a distance from camera position to the tracking body, then if that's too big than you want move it some by the distance you want to get it back into range. I could write up some code on it, but i'm jsut starting my project right now and will need a little time to figure out the best solution to adding in that code.

Apr 21, 2010 at 3:46 PM

Thanks, RC!

May 3, 2010 at 3:39 PM

I did get it finally working. Sorry, I never saw your message until now (should've enabled subscription!). Anyways I don't remember what I had to do to get it working. I'll post it if you want. I totally forgot about this post.

And by the way, GREAT CAMERA!

May 5, 2010 at 12:24 AM

No problem, for some reason i keep forgetting i ask stuff on this forum :P

You're welcome :)

Nov 4, 2010 at 4:30 PM

I’ve read form the community discussions that this camera class is very well implemented and I would like to have a look at it working. I’m aware that this is old post, but I feel this is the best place to address my problem.

As instructed I copied the class code, upon trying to build the code I got the problem mentioned above by StormBoy and fixed it using the post by genbox. However unlike StormBoy upon fixing this problem I still have a problem building the camera.

'FarseerPhysics.Collision.AABB' does not contain a definition for 'Max' and no extension method 'Max' accepting a first argument of type 'FarseerPhysics.Collision.AABB' could be found (are you missing a using directive or an assembly reference?)

Is this a known problem with a known fix, or is it my setup I’ve changed nothing in the original code apart from the fix mentioned by genbox above.

Nov 7, 2010 at 3:49 AM
Edited Nov 7, 2010 at 3:50 AM

If your problem happens to be what I also ran into, I changed

if (camAABB.Contains(texAABB.Min) || camAABB.Contains(texAABB.Max))

to

if (camAABB.Contains(ref texAABB.LowerBound) || camAABB.Contains(ref texAABB.UpperBound))

and I haven't run into any issues, but I haven't done much with the camera other than create it in my game and zoom in and out...