XNA - Moving Background Calculations
Posted
by
Jesse Emond
on Game Development
See other posts from Game Development
or by Jesse Emond
Published on 2011-03-14T04:55:01Z
Indexed on
2011/03/14
8:19 UTC
Read the original article
Hit count: 350
Hi,
My question is relatively hard to explain(for me, at least), so I'll go one step at a time and just tell me in the comments if it's not clear enough.
So I'm making a "Defend Your Castle" type 2D game, where two players own a castle and create units that will move horizontally to try to destroy the opponent's base. Here's a screenshot of the game:
The distance between both castles is much bigger in a real game though, bigger than the screen's width actually.
Because the distance is bigger than the screen's width, I had to implement a simple 2D camera: Camera2D
, which only holds a Location Vector2 (and I always make sure this camera is within the field area).
Then, I just move all the game elements(castles, units, health bars) by that location, so that if a unit is at (5, 0), and the camera's location is (5, 0), then the unit's position will be moved by 5 units to the left, making it (0, 0) on the screen.
At first, I simply used a static background with mountains and clouds(yeah, those are supposed to be mountains and clouds). Obviously, this looked awful: when you moved the camera, the background would stay immobile.
Instead, I'd like to make a moving background, kind of a "scrolling" one. But rather than making a background with the same width as the distance between the castles, I'd like to make one that is a little bit smaller(but still bigger than the screen's width). I thought this would create an effect of "distance" with the background(but it might just look awful, too).
Here's the background I'm testing with:
I tried different ways, but none of them seems to work. I tried this:
float backgroundFieldRatio = BackgroundTexture.Width / fieldWidth;//find the ratio between the background and the field.
float backgroundPositionX = -cam.Location.X * backgroundFieldRatio;//move the background to the left
When I run this with fieldWith = 1600
, BackgroundTexture.Width = 1500
and while looking at the rightmost area, the background is offset to the left by a too big amount, and we can see the black clear color in the back, as you can see here:
I hope I explained properly what I'm trying to achieve.
Thank you for your time.
Note: I didn't know what to look for on Google, so I thought I'd ask here.
© Game Development or respective owner