Hi, I'm working on a 2D game and I was working on the scrolling background but whatever I try it doesn't get it scrolled.
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
//The size of the Sprite
public Rectangle Size;
//Used to size the Sprite up or down from the original image
public float Scale = 1.0f;
// Create an instance of Texture2D that will
// contain the background texture.
Texture2D background;
// Create a Rectangle that will definee
// the limits for the main game screen.
Rectangle mainFrame;
private GamePadState gamePadState;
private KeyboardState keyboardState;
public class Camera
{
public Camera(Viewport viewport)
{
Origin = new Vector2(viewport.Width / 2.0f, viewport.Height / 2.0f);
Zoom = 1.0f;
}
public Vector2 Position { get; set; }
public Vector2 Origin { get; set; }
public float Zoom { get; set; }
public float Rotation { get; set; }
public Matrix GetViewMatrix(Vector2 parallax)
{
// To add parallax, simply multiply it by the position
return Matrix.CreateTranslation(new Vector3(-Position * parallax, 0.0f)) *
// The next line has a catch. See note below.
Matrix.CreateTranslation(new Vector3(-Origin, 0.0f)) *
Matrix.CreateRotationZ(Rotation) *
Matrix.CreateScale(Zoom, Zoom, 1) *
Matrix.CreateTranslation(new Vector3(Origin, 0.0f));
}
}
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
graphics.IsFullScreen = true;
}
protected override void Initialize()
{
gamePadState = GamePad.GetState(PlayerIndex.One);
keyboardState = Keyboard.GetState();
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Load the background content.
background = Content.Load<Texture2D>("Images\\muur");
// Set the rectangle parameters.
mainFrame = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
// Draw the background.
// Start building the sprite.
spriteBatch.Begin();
// Draw the background.
spriteBatch.Draw(background, mainFrame, Color.White);
// End building the sprite.
spriteBatch.End();
base.Draw(gameTime);
}
}
How can I achieve this functionality?
I don't see where you use the camera transform...
you should have a parallax vector and update it...
Vector2 parallax_position;
float parallax_speed;
public void Update (Gametime time)
{
parallax_position += parallax_speed * Vector2.UnitX * (float) time.elapsed.totalseconds;
}
and then in Draw method, you should use it in your spritebatch....
public void Draw()
{
spriteBatch.begin(..,...,..,..,.., GetCameraTransform(Parallax));
...
}
Related
I am trying to use Mouse.GetState() for my menu selection. Currently, it will only highlight if I hover over a region left and up from where the menu is. I used DrawString to display the mouses coordinates and found that the 0,0 point wasn't in the top left of my monitor or in the top left of the game window. It was somewhere about 100,100 pixels from the top left of the screen. Also, the 0,0 point moves every time I run the programme.
I looked at others people who have had the same problem but wasn't able to solve it. I tried using Mouse.WindowHandle = this.Window.Handle; in my Initialize() but it didn't nothing. I have two monitors and when I forced the game in fullscreen it would open on my second monitor so I disabled it but the problem remains.
here is a link to my code http://pastebin.com/PNaFADqp
Game1 class:
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont spriteFont;
public const int WINDOW_HEIGHT = 800;
public const int WINDOW_WIDTH = 600;
public int tree;
public TitleScreen titleScreen;
public SATDemo satDemo;
public SeparatingAxisTest separatingAxisTest;
public SATWithAABB sATWithAABB;
GameState currentState;
public static Dictionary<string, Texture2D> m_textureLibrary = new Dictionary<string, Texture2D>();
public static Dictionary<string, SpriteFont> m_fontLibrary = new Dictionary<string, SpriteFont>();
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferHeight = WINDOW_HEIGHT;
graphics.PreferredBackBufferWidth = WINDOW_WIDTH;
}
protected override void Initialize()
{
Mouse.WindowHandle = this.Window.Handle;
//enable the mousepointer
IsMouseVisible = true;
currentState = GameState.TitleScreen;
//sets the windows mouse handle to client bounds handle
base.Initialize();
}
public void RequestSATDemo()
{
currentState = GameState.RequestSATDemo;
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
m_textureLibrary.Add("Pixel", Content.Load<Texture2D>("White_Pixel"));
m_fontLibrary.Add("Font", Content.Load<SpriteFont>("MotorwerkOblique"));
titleScreen = new TitleScreen();
satDemo = new SATDemo();
separatingAxisTest = new SeparatingAxisTest();
sATWithAABB = new SATWithAABB();
}
public void RequestSeparatingAxisTest()
{
currentState = GameState.SeparatingAxisTest;
}
public void RequestSATWithAABB()
{
currentState = GameState.SATWithAABB;
}
protected override void Update(GameTime gameTime)
{
MouseTestState = Mouse.GetState();
switch (currentState)
{
case GameState.TitleScreen:
{
titleScreen.Update(gameTime);
break;
}
case GameState.SeparatingAxisTest:
{
separatingAxisTest.Update(gameTime);
break;
}
case GameState.SATWithAABB:
{
sATWithAABB.Update(gameTime);
break;
}
case GameState.Exit:
{
Exit();
break;
}
default:
{
titleScreen.Update(gameTime);
break;
}
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
spriteBatch.Begin();
spriteBatch.DrawString(m_fontLibrary["Font"], MouseTestState.ToString(), new Vector2(0, 0), Color.White);
switch (currentState)
{
case GameState.TitleScreen:
{
titleScreen.Draw(spriteBatch, spriteFont);
break;
}
case GameState.SeparatingAxisTest:
{
separatingAxisTest.Draw(gameTime, spriteBatch);
break;
}
case GameState.SATWithAABB:
{
sATWithAABB.Draw(gameTime, spriteBatch);
break;
}
case GameState.Exit:
{
Exit();
break;
}
default:
{
titleScreen.Update(gameTime);
break;
}
}
spriteBatch.End();
base.Draw(gameTime);
}
}
TitleScreen class:
public class TitleScreen : Screen
{
List<Button> buttonList = new List<Button>();
public Menu mainMenu;
public TitleScreen()
{
mainMenu = new Menu(new Vector2(200, 100), buttonList, 0);
buttonList.Add(new PushButton("Separating Axis Test"));
buttonList.Add(new PushButton("SAT With AABB"));
buttonList.Add(new PushButton("Awesome"));
buttonList.Add(new PushButton("Awesomere"));
buttonList.Add(new PushButton("Awesomere"));
}
public override void Update(GameTime gametime)
{
mainMenu.Update(gametime);
}
public void Draw(SpriteBatch sB, SpriteFont sF)
{
mainMenu.Draw(sB, sF);
}
}
PushButton class:
public class PushButton : Button
{
string m_text;
SpriteFont m_font;
Color m_static, m_onClick, m_onHover;
Texture2D m_sprite2D, m_onClick2D;
static public int Pbuttoncount;
//click processing
bool m_clickedInside = false,
m_releasedInside = false,
m_OnClicked = false,
selected = false;
Rectangle drawRectangle;
public PushButton(string Text)
{
m_text = Text;
drawRectangle = new Rectangle((int)Menu.m_position.X, (int)Menu.m_position.Y + (15 * Pbuttoncount), 200, 15);
ButtonRegion = new Rectangle((int)Position.X, (int)Position.Y, 200, 15);
Pbuttoncount++;
}
public PushButton(Rectangle ButtonRegion, SpriteFont Font, string Text, Color Static, Color OnClick, Color OnHover)
{
m_buttonRegion = ButtonRegion;
m_font = Font;
m_text = Text;
m_static = Static;
m_onClick = OnClick;
m_onHover = OnHover;
// drawRectangle = ButtonPosition(m_buttonRegion);
}
public PushButton(Rectangle ButtonRegion, Texture2D Sprite2D, Texture2D OnClick2D)
{
m_buttonRegion = ButtonRegion;
m_sprite2D = Sprite2D;
m_onClick2D = OnClick2D;
//drawRectangle = ButtonPosition(m_buttonRegion);
}
public override void Update(GameTime gameTime)
{
MouseState currentMouse = Mouse.GetState();
selected = MouseState(drawRectangle, currentMouse);
m_clickedInside = ClickInside(currentMouse, m_lastMouseState);
ReleaseInside(currentMouse, m_lastMouseState);
if (selected && m_clickedInside && m_releasedInside)
m_OnClicked = true;
else
m_OnClicked = false;
m_lastMouseState = currentMouse;
}
public override void Draw(SpriteBatch spriteBatch, SpriteFont spriteFont, int buttonCount, Vector2 Position)
{
spriteBatch.Draw(Game1.m_textureLibrary["Pixel"], new Rectangle((int)Position.X + 10, (int)(Position.Y + 15 * buttonCount), 180, 15), Color.Wheat);
if (selected)
spriteBatch.DrawString(Game1.m_fontLibrary["Font"], m_text, new Vector2(Position.X + 15, Position.Y + 15 * buttonCount), Color.Orange);
else
spriteBatch.DrawString(Game1.m_fontLibrary["Font"], m_text, new Vector2(Position.X + 15, Position.Y + 15 * buttonCount), Color.Black);
}
}
Menu class:
public class Menu
{
List<Button> m_buttonList;
float m_transparency;
public int n = 0;
public Rectangle buttonRegion, m_menuRegion, m_dimensions;
static public Vector2 m_position;
int m_WINDOW_HEIGHT = Game1.WINDOW_HEIGHT;
int m_WINDOW_WIDTH = Game1.WINDOW_WIDTH;
private Game1 m_managerClass;
public Menu(Vector2 Position, List<Button> ButtonList, float Transparency)
{
m_position = Position;
m_buttonList = ButtonList;
m_transparency = Transparency;
m_managerClass = new Game1();
}
public Rectangle MenuRegion
{
get { return m_menuRegion; }
set { m_menuRegion = value; }
}
static public Vector2 Position
{
get { return m_position; }
}
public void Update(GameTime gametime)
{
for (int i = 0; i < m_buttonList.Count; i++)
{
m_buttonList[i].Update(gametime);
if (m_buttonList[0].OnClicked)
{
SeperatingAxisTest();
}
}
}
public void Draw(SpriteBatch sB, SpriteFont sF)
{
sB.Draw(Game1.m_textureLibrary["Pixel"], new Rectangle((int)m_position.X - 5, (int)m_position.Y - 10, (m_buttonList[0].ButtonRegion.Width + 10), (m_buttonList[0].ButtonRegion.Height * m_buttonList.Count) + 20), Color.Blue);
for (int i = 0; i < m_buttonList.Count; i++)
{
m_buttonList[i].Draw(sB, sF, i, new Vector2(Position.X, Position.Y));
}
}
private void SeperatingAxisTest()
{
m_managerClass.RequestSeparatingAxisTest();
}
}
Program class:
public static class Program
{
[STAThread]
static void Main()
{
using (var game = new Game1())
game.Run();
}
}
Let me know if you need anything else. I'm still learning and will sell my soul to you for an answer.
Your Menu class is creating a new instance of Game1. This is, most likely, not what you want, since Game1 is instantiated in the entry point for you app. The Game1 instance has an instance of TitleScreen, which in turn has an instance of the Menu class, so a Menu should have no business creating its own game.
When this (other) instance is created, it invokes platform-specific (Windows) methods, creates an additional window handle (which is never shown) and configures the Mouse.WindowHandle.
And btw, setting WindowHandle manually does absolutely nothing in Monogame, so all these sources mentioning that are talking about XNA.
So, there are several remarks:
You should probably have a "screen manager" class which contains the current screen. It is strange to have a field of type TitleScreen in your game class, it should at least be of the base type (Screen), so that the game class draws and updates each screen transparently.
If you need a reference to the game class anywhere, don't instantiate a new one, but rather pass it along through the constructor.
m_managerClass is a bad name for a field which is actually a Game. Also google for C# naming conventions. Perhaps you even might want to download an existing monogame game template, e.g. check some of the samples online; the NetRumble sample seems to implement a screen manager.
Remove the Mouse.WindowHandle line, it should be set to your one-and-only game window by default.
tl;dr add the Game1 as a parameter wherever you might need it (but only where you need it).
abstract class Screen
{
private readonly Game1 _game;
public Game1 Game
{ get { return _game; } }
public Screen(Game1 game)
{
_game = game;
}
}
class TitleScreen : Screen
{
public TitleScreen(Game1 game)
: base(game)
{ ... }
}
class Menu
{
private readonly Screen _screen;
public Menu(Screen parentScreen, Vector2 pos, List<Button> list, float alpha)
{
_screen = parentScreen;
...
// if you need the game instance, just use _screen.Game
}
}
I need to create an image slideshow in my app (i.e. the image should be changed at a regular interval of time with a fade in / fade out effect). I have tried some code, but it throws illegal exception.
Is there any option to change images in picture scroll field programatically? i.e. from a thread or something?
public class SlideTransition extends MainScreen {
final Bitmap image000 = Bitmap.getBitmapResource("img1.jpg");
final Bitmap image001 = Bitmap.getBitmapResource("img2.jpg");
final Bitmap image002 = Bitmap.getBitmapResource("img3.jpg");
final BitmapField animationField = new BitmapField(image000);
int counter = 0;
Timer animationTimer = new Timer();
TimerTask animationTask;
public SlideTransition() {
animationTask = new TimerTask() {
public void run() {
if (counter == 0) {
animationField.setBitmap(image000);
}
if (counter == 1) {
animationField.setBitmap(image001);
}
if (counter == 2) {
animationField.setBitmap(image002);
counter = -1;
}
counter++;
}
};
animationTimer.scheduleAtFixedRate(animationTask, 0, 100);
add(animationField);
}
}
The code posted will throw an IllegalStateException because it is attempting to modify a UI element directly from a background (timer) thread:
animationField.setBitmap(image000);
You need to use UiApplication.getUiApplication().invokeLater(), or something similar, to modify the UI from a background thread.
Also, you can have your timer continuously adjust the bitmap field's alpha value (opacity) to produce a fade effect.
Here's an example, starting with the code you provided:
public class SlideTransition extends MainScreen {
private final Bitmap image000 = Bitmap.getBitmapResource("img1.jpg");
private final Bitmap image001 = Bitmap.getBitmapResource("img2.jpg");
private final Bitmap image002 = Bitmap.getBitmapResource("img3.jpg");
private AlphaBitmapField animationField = new AlphaBitmapField(image000);
private Timer animationTimer = new Timer();
private TimerTask animationTask;
private final int animationPeriodMsec = 40; // 25 Hz animation timer
public SlideTransition() {
animationTask = new AnimationTask();
add(animationField);
animationTimer.scheduleAtFixedRate(animationTask, 0, animationPeriodMsec);
}
// I separated your anonymous timer task into its own class for readability
private class AnimationTask extends TimerTask {
private final int fadeDurationMsec = 500;
private final int displayDurationMsec = 1500;
private final int fadeInEndCount = fadeDurationMsec / animationPeriodMsec;
private final int fadeOutStartCount = (fadeDurationMsec + displayDurationMsec) / animationPeriodMsec;
private final int endCount = (2 * fadeDurationMsec + displayDurationMsec) / animationPeriodMsec;
private int imgCounter = 0;
private int cycleCounter = 0;
public void run() {
if (cycleCounter >= endCount) {
cycleCounter = 0;
}
Bitmap newImage = null;
if (cycleCounter == 0) {
// time to switch the images
if (imgCounter == 0) {
newImage = image000;
} else if (imgCounter == 1) {
newImage = image001;
} else if (imgCounter == 2) {
newImage = image002;
imgCounter = -1;
}
imgCounter++;
}
// assign final variables to use inside a UI thread Runnable
final Bitmap currentImage = newImage;
final int i = cycleCounter;
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
if (i == 0) {
// switch images, and start with the image invisible (alpha = 0)
animationField.setAlpha(0);
animationField.setBitmap(currentImage);
} else if (i <= fadeInEndCount) {
// fade in by changing alpha
animationField.setAlpha(i * 255 / fadeInEndCount);
} else if (i >= fadeOutStartCount) {
// fade out by changing alpha
animationField.setAlpha(255 + (fadeOutStartCount - i) * 255 / (endCount - fadeOutStartCount));
}
}
});
cycleCounter++;
}
}
// this class extends BitmapField to allow alpha adjustment, and automatic repainting
private class AlphaBitmapField extends BitmapField {
private int _alpha;
public AlphaBitmapField(Bitmap img) {
super(img);
}
public void setAlpha(int alpha) {
if (alpha != _alpha) {
_alpha = alpha;
// force a repaint
invalidate();
}
}
protected void paint(Graphics graphics) {
graphics.setGlobalAlpha(_alpha);
super.paint(graphics);
}
}
}
I changed the time values from your code, but you can modify them to whatever you like. I had the animation timer run at 25 cycles per second. I find that this is a reasonable value for smartphone animations. It's fast enough to look fairly smooth, but is only about twice the rate that the human eye can process information like this ... any faster is probably wasteful.
I defined constants that you can use to control the length of time that the fade in and fade out takes (fadeDurationMsec) and the time that each image is displayed between fade in and fade out (displayDurationMsec). All values are in milliseconds.
Helpful References
BlackBerry AnimatedGIFField sample code.
BlackBerry forums thread about fade in / fade out
I am trying to build a very simple XNA project.
Every 5 seconds a new ball should be spawned which will bounce of the walls.
For some reason it doesn't create multiple instances of my ball. I can't seem to figure out what i'm doing wrong.
Was hoping someone here could help me discover my errors.
Here is my code Game1.cs class
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace BallBounce
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
public static SpriteBatch spriteBatch;
Ball ball;
Ball ball2;
Ball[] balls;
int maxBalls = 1;
Texture2D ballTexture;
Texture2D ballTexture2;
Vector2 position;
Vector2 position2;
int spawnTime = 0;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
ballTexture = Content.Load<Texture2D>("Bitmap1");
ballTexture2 = Content.Load<Texture2D>("Bitmap2");
Random r = new Random();
int randomNumberX = r.Next(0, 400);
int randomNumberY = r.Next(0, 400);
position = new Vector2(randomNumberX, randomNumberY);
position2 = new Vector2(randomNumberY, randomNumberX);
ball = new Ball(this, ballTexture, position);
ball2 = new Ball(this, ballTexture2, position2);
Components.Add(ball);
// Components.Add(ball2);
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
spawnTime += (int)gameTime.ElapsedGameTime.Milliseconds;
// Console.WriteLine(spawnTime + " " + maxBalls);
if(spawnTime >= 500)
{
maxBalls += 1;
for(int i = 0; i < maxBalls; i++)
{
//balls[i] = new Ball(this,ballTexture);
//Components.Add(balls[i]);
}
spawnTime = 0;
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
}
And here is my Ball.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace BallBounce
{
public class Ball : Microsoft.Xna.Framework.DrawableGameComponent
{
Texture2D texture;
Vector2 speed = new Vector2(4,6);
Vector2 position;
Color color = Color.Blue;
public Ball(Game1 game, Texture2D texture, Vector2 position)
: base(game)
{
this.texture = texture;
Console.WriteLine("=========================BAL---------------");
this.position = position;
Random random = new Random();
int red = random.Next(0, 255);
int green = random.Next(0,255);
int blue = random.Next(0,255);
color = new Color(red,green,blue);
Console.WriteLine(position);
}
public override void Update(GameTime gameTime)
{
this.position = this.position += speed;
if (this.position.Y >= (GraphicsDevice.Viewport.Height - this.texture.Height))
{
speed.Y = speed.Y * -1;
}
if (this.position.Y <= 0)
{
speed.Y = speed.Y * -1;
}
if (this.position.X >= (GraphicsDevice.Viewport.Width - this.texture.Width))
{
speed.X = speed.X * -1;
}
if (this.position.X <= 0)
{
speed.X = speed.X * -1;
}
}
public override void Draw(GameTime gameTime)
{
Game1.spriteBatch.Begin();
Game1.spriteBatch.Draw(texture, position, color);
Game1.spriteBatch.End();
base.Draw(gameTime);
}
}
}
It looks like you're recreating all balls in some array, adding one more every 500 milliseconds (which is 0.5 of a second really). You should just add a new ball to some global list of balls, instead of rewriting all existing balls as you do now.
So I guess you could do this:
if(spawnTime >= 500)
{
Components.Add(new Ball(this, ballTexture));
spawnTime = 0;
}
Your approach doesn't look good, though. Are you sure you want to add balls straight to Components?
I'm currently doing an assignment, on which one of the requirements is for a random object to appear on screen and move across. Being new to XNA, i do not know where to even begin implementing such behaviours to the game, thus would really appreciate if someone could give me a nudge towards the right direction.
I'm only really accustomed to invoking something when a key is pressed, however with something completely random, this can't be done. as far as i am aware of.
Thank you.
You need to create and set up a sprite for the UFO first. In your protected override void Update(GameTime gameTime) code you simply need to get the current time and compare it to the rules in which you wish to apply. Then update if you wish to draw and "move" the sprite. Here is an example:
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
#endregion
public class Game : Microsoft.Xna.Framework.Game {
#region Game Settings
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
GraphicsDevice device;
int screenWidth = 800;
int screenHeight = 600;
bool fullscreen = false;
string title = "MyGame";
string origionaltitle;
float frames = 0;
float framesPerSecond = 0;
int startTime;
int currentTime;
int nextTime;
#endregion
struct sprite {
public string TextureName;
public Texture2D Texture;
public Vector2 Position;
public Vector2 Speed;
public Color[] TextureData;
};
bool DrawUFO = false;
sprite ufo = new sprite();
public Game() {
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void LoadContent() {
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
device = graphics.GraphicsDevice;
// TODO: use this.Content to load your game content here
ufo.TextureName = "ufo";
ufo.Texture = Content.Load<Texture2D>(ball.TextureName);
ufo.TextureData = new Color[ufo.Texture.Width *ufo.Texture.Height];
ufo.Texture.GetData(ball.TextureData);
}
protected override void Initialize() {
// TODO: Add your initialization logic here
ufo.Position = new Vector2(10f, 10.0f);
ufo.Speed = new Vector2(0.0f, 10.0f);
//
// Set up game window
graphics.PreferredBackBufferWidth = screenWidth;
graphics.PreferredBackBufferHeight = screenHeight;
graphics.IsFullScreen = fullscreen;
graphics.ApplyChanges();
origionaltitle = title;
Window.Title = title;
//
// Set the initial time
startTime = DateTime.Now.Second;
//
// Set "random"/next time for ufo to be rendered
nextTime = startTime + rand.Next(2);
//
base.Initialize();
}
protected override void Update(GameTime gameTime) {
//
// Set the current time
currentTime = DateTime.Now.Second;
//
// if not drawing ufo then
if(!DrawURO) {
//
// check current time and compare it with the next time
if( currentTime == nextTime ) {
DrawURO = true;
}
} else {
//
// Update UFO position (aka move it)
ufo.Posistion += ball.Speed *(float)gameTime.ElapsedGameTime.TotalSeconds;
//
// if ufo goes of the screen then
if(ufo.Position.Y > screenHeight) {
//
// Reset ufo
DrawURO = false;
ufo.Position.X = 10.0f;
ufo.Position.Y = 10.0f;
//
// set next time to render
nextTime = currentTime + rand.Next(2);
}
}
}
protected override void Draw(GameTime gameTime) {
graphics.GraphicsDevice.Clear(Color.Black);
// TODO: Add your drawing code here
spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
if(DrawUFO == true) {
spriteBatch.Draw(ufo.Texture, ufo.Position, Color.White);
}
spriteBatch.End();
//
base.Draw(gameTime);
}
}
I copied this from some code i did at college a few years a ago, so apologies for any bugs.
How do I implement an image button in BlackBerry?
here you go, complete code:
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.ButtonField;
/**
* Button field with a bitmap as its label.
*/
public class BitmapButtonField extends ButtonField {
private Bitmap bitmap;
private Bitmap bitmapHighlight;
private boolean highlighted = false;
/**
* Instantiates a new bitmap button field.
*
* #param bitmap the bitmap to use as a label
*/
public BitmapButtonField(Bitmap bitmap, Bitmap bitmapHighlight) {
this(bitmap, bitmapHighlight, ButtonField.CONSUME_CLICK|ButtonField.FIELD_HCENTER|ButtonField.FIELD_VCENTER);
}
public BitmapButtonField(Bitmap bitmap, Bitmap bitmapHighlight, long style) {
super(style);
this.bitmap = bitmap;
this.bitmapHighlight = bitmapHighlight;
}
/* (non-Javadoc)
* #see net.rim.device.api.ui.component.ButtonField#layout(int, int)
*/
protected void layout(int width, int height) {
setExtent(getPreferredWidth(), getPreferredHeight());
}
/* (non-Javadoc)
* #see net.rim.device.api.ui.component.ButtonField#getPreferredWidth()
*/
public int getPreferredWidth() {
return bitmap.getWidth();
}
/* (non-Javadoc)
* #see net.rim.device.api.ui.component.ButtonField#getPreferredHeight()
*/
public int getPreferredHeight() {
return bitmap.getHeight();
}
/* (non-Javadoc)
* #see net.rim.device.api.ui.component.ButtonField#paint(net.rim.device.api.ui.Graphics)
*/
protected void paint(Graphics graphics) {
super.paint(graphics);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap b = bitmap;
if (highlighted)
b = bitmapHighlight;
graphics.drawBitmap(0, 0, width, height, b, 0, 0);
}
public void setHighlight(boolean highlight)
{
this.highlighted = highlight;
}
}
Use RIM's Advanced UI Pack.
http://supportforums.blackberry.com/t5/Java-Development/Implement-advanced-buttons-fields-and-managers/ta-p/488276
This contains a BitmapButton field and a great number of of useful UI tools.
(No doubt Reflogs example is good, but I think for new BB developers landing on this page the Advanced UI pack is more beneficial)
perfect ImageButton for Blackberry , According to user point of view a Imagebutton should have four states
1. Normal
2. Focus
3. Selected Focus
4. Selected unfocus
the Following code maintain all four states (Field-Change-Listener and Navigation)
if you want to maintain all four states than use 1st Constructor, If you just want to handle Focus/Un-Focu state of the button than use 2nd one
########################################
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
public class ImageButton extends Field
{
Bitmap mNormalIcon;
Bitmap mFocusedIcon;
Bitmap mActiveNormalIcon;
Bitmap mActiveFocusedIcon;
Bitmap mActiveBitmap;
String mActiveText;
int mHeight;
int mWidth;
boolean isStateActive = false;
boolean isTextActive = false;
public boolean isStateActive()
{
return isStateActive;
}
public ImageButton(Bitmap normalIcon, Bitmap focusedIcon)
{
super(Field.FOCUSABLE | FIELD_VCENTER);
mNormalIcon = normalIcon;
mFocusedIcon = focusedIcon;
mActiveBitmap = normalIcon;
mActiveFocusedIcon = focusedIcon;
mActiveNormalIcon = normalIcon;
// isTextActive = false;
}
public ImageButton(Bitmap normalIcon, Bitmap focusedIcon, Bitmap activeNormalIcon, Bitmap activeFocusedIcon)
{
super(Field.FOCUSABLE | FIELD_VCENTER);
mNormalIcon = normalIcon;
mFocusedIcon = focusedIcon;
mActiveFocusedIcon = activeFocusedIcon;
mActiveNormalIcon = activeNormalIcon;
mActiveBitmap = normalIcon;
// isTextActive = true;
}
protected void onFocus(int direction)
{
if ( !isStateActive )
{
mActiveBitmap = mFocusedIcon;
}
else
{
mActiveBitmap = mActiveFocusedIcon;
}
}
protected void onUnfocus()
{
super.onUnfocus();
if ( !isStateActive )
{
mActiveBitmap = mNormalIcon;
}
else
{
mActiveBitmap = mActiveNormalIcon;
}
}
protected boolean navigationClick(int status, int time)
{
mActiveBitmap = mActiveNormalIcon;
toggleState();
invalidate();
fieldChangeNotify(1);
return true;
}
public void toggleState()
{
isStateActive = !isStateActive;
}
public int getPreferredWidth()
{
return mActiveBitmap.getWidth() + 20;
}
public int getPreferredHeight()
{
return mActiveBitmap.getHeight() + 10;
}
protected void layout(int width, int height)
{
mWidth = getPreferredWidth();
mHeight = getPreferredHeight();
setExtent(mWidth, mHeight);
}
protected void paint(Graphics graphics)
{
graphics.drawBitmap(0, 5, mWidth, mHeight, mActiveBitmap, 0, 0);
// graphics.setColor(0xff0000);
// graphics.drawText(mActiveText, ( mActiveBitmap.getWidth() -
// this.getFont().getAdvance("ON") ) / 2, mActiveBitmap.getHeight());
}
protected void drawFocus(Graphics graphics, boolean on)
{
}
public void activate()
{
mActiveBitmap = mActiveNormalIcon;
isStateActive = true;
invalidate();
}
public void deactivate()
{
mActiveBitmap = mNormalIcon;
isStateActive = false;
invalidate();
}
}
easiest way to do that:
step 1:draw a image with specific coordinates(imageX,imageY).
step 2:add a method in your Code:
void pointerControl(int x, int y) {
if (x>imageX && x<imageX+imageName.getWidth() && y>imageY && y < imageY+imageName.getHeight) {
//to do code here
}
}
where imageName:name of image
imageX=x coordinate of image(Top-Left)
imageY=y coordinate of image(Top-Left)