c# - XNA - Moving an animated rectangle horizontaly (no user input, but timer) -
here want move animated rectangle horizontaly without user input, using timer, maybe? animated rectangle should move left , right (from starting point end point, whole path = 315 pixels). mean 315 pixels between point 1 (start on left) , point 2 (end on right). here's code: variables:
//sprite texture texture2d texture; //a timer variable float timer = 0f; //the interval (300 milliseconds) float interval = 300f; //current frame holder (start @ 1) int currentframe = 1; //width of single sprite image, not whole sprite sheet int spritewidth = 32; //height of single sprite image, not whole sprite sheet int spriteheight = 32; //a rectangle store 'frame' being shown rectangle sourcerect; //the centre of current 'frame' vector2 origin;
next, in loadcontent()
method:
//texture load texture = content.load<texture2d>("gamegraphics\\enemies\\sprite");
the update()
method:
//increase timer number of milliseconds since update last called timer += (float)gametime.elapsedgametime.totalmilliseconds; //check timer more chosen interval if (timer > interval) { //show next frame currentframe++; //reset timer timer = 0f; } //if on last frame, reset 1 before first frame (because currentframe++ called next next frame 1!) currentframe = currentframe % 2; sourcerect = new rectangle(currentframe * spritewidth, 0, spritewidth, spriteheight); origin = new vector2(sourcerect.width / 2, sourcerect.height / 2);
and finally, draw()
method:
//texture draw spritebatch.draw(texture, new vector2(263, 554), sourcerect,color.white, 0f, origin, 1.0f, spriteeffects.none, 0);
so want move sourcerect
. ir must loop left , right.
your spritebatch.draw()
call keeps using same value destinationrectangle
. how want move? 5 pixels right each frame example? change destinationrectangle
(2nd argument spritebatch.draw()
) to:
new vector2(263 + (currentframe * 5), 554);
edit: example requested comments
class foo { int x; int maxx = 400; void update(gametime gametime) { if (x++ >= maxx) x = 263; } void draw() { spritebatch.draw(texture, new vector2(263 + x, 554), sourcerect,color.white, 0f, origin, 1.0f, spriteeffects.none, 0); } }
you would, of course, keep of current code except spritebatch.draw() call same; adding x
parts.
Comments
Post a Comment