Blackberry Animation Issue on App's Home Screen - blackberry

I am trying to create an Application which has a Home Screen (MyScreen below) animation in Blackberry which makes an image float from the bottom to middle of the screen. Then after that, i want to push another Screen which brings a Login Screen or something (NewScreen below).
I am getting a blank Screen after the animation. On pressing back once, i am getting the Screen i pushed from the Animation Screen. Please guide me: where should i push to get the perfect result?
import net.rim.device.api.animation.AnimatedScalar;
import net.rim.device.api.animation.Animation;
import net.rim.device.api.animation.Animator;
import net.rim.device.api.animation.AnimatorListener;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.TransitionContext;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.UiEngineInstance;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.PopupScreen;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen implements AnimatorListener {
private RectangleToMove _rect;
private Animator _animator;
private Animation _xanimation;
private Animation _yanimation;
private boolean _bAnimating;
public static final int BALL_WIDTH = 50;
public Bitmap splashimg;
static TransitionContext transitionContextIn;
static TransitionContext transitionContextOut;
static UiEngineInstance engine = Ui.getUiEngineInstance();
/**
* Creates a new MyScreen object
*/
public MyScreen() {
EncodedImage img = EncodedImage.getEncodedImageResource("logo.png");
splashimg = img.getBitmap();
_bAnimating = false;
int midScreen = (Display.getWidth() / 2) - img.getWidth()/2;
int endScreen = Display.getHeight();
_rect = new RectangleToMove(midScreen, BALL_WIDTH);
_animator = new Animator(30);
_animator.setAnimatorListener(this);
_yanimation = _animator.addAnimationFromTo(_rect.getY(),
AnimatedScalar.ANIMATION_PROPERTY_SCALAR, endScreen
- BALL_WIDTH, Display.getHeight() / 2-30,
Animation.EASINGCURVE_LINEAR, 3000L);
_yanimation.setRepeatCount(1f);
_yanimation.begin(0);
UiApplication.getUiApplication().pushScreen(new NewScreen());
}
protected void paint(Graphics g) {
if (_bAnimating) {
_rect.draw(g, splashimg);
}
}
public void animatorUpdate() {
invalidate();
doPaint();
}
public void animatorProcessing(boolean processing) {
_bAnimating = processing;
}
}
class RectangleToMove {
private int xPos;
private AnimatedScalar yPos;
public void draw(Graphics g, Bitmap splashimg) {
g.setBackgroundColor(Color.BLACK);
g.clear();
g.setColor(Color.SLATEGRAY);
g.drawBitmap(xPos, yPos.getInt(), splashimg.getWidth(),
splashimg.getHeight(), splashimg, 0, 0);
/*
* g.fillEllipse(xPos,yPos.getInt(),
* xPos+MyScreen.BALL_WIDTH,yPos.getInt(),xPos,
* yPos.getInt()+MyScreen.BALL_WIDTH,0,360);
*/
}
public int getX() {
return xPos;
}
public AnimatedScalar getY() {
return yPos;
}
RectangleToMove(int x, int y) {
xPos = x;
yPos = new AnimatedScalar(y);
}
}

I'm not 100% sure I understand your problem, but I edited your question to describe what I think is the problem.
When your animation ends, you're seeing a blank white screen that you don't want. You have to press Back/ESC to make the white screen disappear, so that you can get back to your login screen (NewScreen). I assume you don't want to see the initial animation screen after it first shows (probably because it's a loading, or splash screen).
In order to do this, you need to wait until the animation completes before pushing your second screen. So, remove this call to pushScreen:
UiApplication.getUiApplication().pushScreen(new NewScreen());
that you have in the MyScreen constructor. At that point, the animation has not completed, so it's too soon to push the NewScreen.
Then, push the screen when the AnimatorListener is told that the animation has stopped. If you don't want the animation screen to be visible, when backing through your screens, then pop it after pushing the second screen:
public void animatorProcessing(boolean processing) {
_bAnimating = processing;
if (!processing) {
// the animation is complete
UiApplication.getUiApplication().pushScreen(new NewScreen());
// use this line if the instance of `MyScreen` should not be
// visible after the user presses Back/ESC:
UiApplication.getUiApplication().popScreen(this);
}
}

Related

Path Line using in andengine

I want to make a paint game in andengine. There is my codes. How can i use them in andengine? Or is there anything like drawPath in andengine? I tried to add Rects or Lines for drawing but my FPS was 10-15.
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class SingleTouchEventView extends View {
private Paint paint = new Paint();
private Path path = new Path();
public SingleTouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);
setBackgroundColor(Color.WHITE);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
// nothing to do
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
There are several ways to accomplish what you want.
create Rectangles (not lines since they differ from device to device) and add them to the scene to get a path. Use object pools to reuse your objects (Rectangles).
if the first approach doesn't perform well then you could also draw directly on an empty texture using canvas.
there is a class called RenderTexture on which you can draw entities. Use such a RenderTexture and draw your lines to it. create a sprite using this Texture and add it to the scene.

gotoAndPlay not finding Frame Label AS3

I'm trying to build a simple Flash game where the user drags a sombrero onto a cactus. I've got it so that when you drag the sombrero anywhere but the cactus, it snaps back to it's original position. I had it so when you drag it onto the cactus, it stays there.
What I want is when the user drags the sombrero onto the cactus, it takes you to a screen that says "YAY! Play again?" I put a gotoAndPlay() inside my if statement:
if(dropTarget.parent.name == "cactus")
{
//scaleX = scaleY = 0.2;
//alpha = 0.2;
//y = stage.stageHeight - height - -100;
//buttonMode = false;
//removeEventListener(MouseEvent.MOUSE_DOWN, down);
gotoAndPlay("playAgain");
trace("dropped on cactus");
}
else
{
returnToOriginalPosition();
}
I labeled my second frame as "playAgain." I get an error saying:
ArgumentError: Error #2109: Frame label playAgain not found in scene playAgain.
at flash.display::MovieClip/gotoAndPlay()
at net.dndgtal.Cactus_Game::sombrero/stageUp()
I have Googled and checked and double checked all the suggestions, but cannot get it to work. I don't have a scene "playAgain," only "scene1." I've tried specifying both the scene and the frame- that doesn't work either. And I tried just putting in gotoAndPlay(2), for frame two, but that just does nothing.
Am I missing something? Any help would be appreciated. Here is all of my code if that helps:
package net.dndgtal.Cactus_Game
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.geom.Point;
public class sombrero extends MovieClip
{
protected var OriginalPosition:Point;
public function sombrero ()
{
OriginalPosition = new Point(x, y);
buttonMode = true;
addEventListener ( MouseEvent.MOUSE_DOWN, down );
//trace("sombrero constructor");
}
protected function down (event:MouseEvent):void
{
parent.addChild(this);
startDrag();
stage.addEventListener(MouseEvent.MOUSE_UP, stageUp);
//trace("DOWN");
}
protected function stageUp(event:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, stageUp);
stopDrag();
if (dropTarget)
{
if(dropTarget.parent.name == "cactus")
{
//scaleX = scaleY = 0.2;
//alpha = 0.2;
//y = stage.stageHeight - height - -100;
//buttonMode = false;
//removeEventListener(MouseEvent.MOUSE_DOWN, down);
gotoAndPlay("playAgain");
trace("dropped on cactus");
}
else
{
returnToOriginalPosition();
}
}
else
{
returnToOriginalPosition();
}
}
protected function returnToOriginalPosition(): void
{
x = OriginalPosition.x;
y = OriginalPosition.y;
}
}
}
Thanks! Let me know if you have any questions.
Your issue is likely one of scope. When you use gotoAndPlay("playAgain"), it will take the current timeline (scope), which is the sombrero class, and attempt to find a frame label or scene called "playAgain" on it's timeline.
Presumably, you want the main timeline to gotoAndPlay the frame label "playAgain", not the sombrero.
To access the main timeline, you can use MovieClip(root).gotoAndPlay("playAgain").
If it's not the main timeline, but the parent of sombrero, you can access it with MovieClip(parent).gotoAndPlay("playAgain")
If the relationship between the sombrero and whichever timeline your trying to advance is more complicated than that, then you could pass in a reference to it in your sombrero constructor:
private var targetTimeline:MovieClip;
public function sombrero (targetTimeline_:MovieClip)
{
targetTimeline = targetTimeline_;
//...rest of constructor code
And then:
if(dropTarget.parent.name == "cactus"){
targetTimeline.gotoAndPlay("playAgain");
And when you create the sombrero, pass in the target timeline:
var hat:sombrero = new sombrero(target);

XNA mouse 'position relative-to' changes every build

Okay so I'm starting to make a main menu for a small flash game and to do this I want to use the mouse to click on buttons etc. I have a button class in which I create two rectangles: a rectangle for the button and a rectangle for the mouse based on its X and Y, 1 pixel by 1 pixel. I use Rectangle.Intersects to check if they are touching before seeing if left mouse button is down. Problem is, the thing the mouse position is relative to changes every time so no matter where the mouse button is on the screen, it's never the same co-ordinates as in a different build in that exact same position. I seriously just need ideas now as I'm running out. If I didn't explain it very well or you need further details to help please ask - I WOULD BE SO GRATEFUL.
Will post back if I find an answer
Update - Okay here's the button class
class OnScreenButton
{
public Texture2D texture;
Vector2 position;
Rectangle rectangle;
Color colour = new Color(255, 255, 255, 255);
public Vector2 size;
public OnScreenButton(Texture2D newtexture, GraphicsDevice graphics)
{
texture = newtexture;
// ScreenW = 500, ScreenH = 600
// Img W = 80, Img H = 20
size = new Vector2(graphics.Viewport.Width / 10, graphics.Viewport.Height / 30);
size = new Vector2(texture.Width, texture.Height);
}
bool down;
public bool isClicked;
public void Update(MouseState mouseState)
{
rectangle = new Rectangle((int)position.X, (int)position.Y, (int)size.X, (int)size.Y);
Rectangle mouseRectangle = new Rectangle(mouseState.X, mouseState.Y, 1, 1);
if (mouseRectangle.Intersects(rectangle))
{
if (colour.A == 255)
{
down = false;
}
if (colour.A == 0)
{
down = true;
}
if (down)
{
colour.A += 3;
}
else
{
colour.A -= 3;
}
if (mouseState.LeftButton == ButtonState.Pressed)
{
isClicked = true;
}
}
else if (colour.A < 255)
{
colour.A += 3;
isClicked = false;
colour.A = (255);
}
}
public void SetPosition(Vector2 newPos)
{
position = newPos;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, rectangle, colour);
}
}
}
(Sorry for weird formatting, brand new to stack overflow and the posting is still a little confusing)
Here is some other code I think is relevent...
Game.1 initializing stuff
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
protected override void Initialize()
{
// TODO: Add your initialization logic here
Mouse.WindowHandle = Window.Handle;
base.Initialize();
}
public Main()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
KeyboardState keyboardState;
MouseState mouseState;
Main menu update routine...
private void UpdateMainMenu(GameTime gameTime)
{
// Button options
if (buttonPlay.isClicked == true)
{
CreateNewGame();
currentGameState = GameState.playing;
}
buttonPlay.Update(mouseState);
if (buttonExit.isClicked == true)
{
this.Exit();
}
buttonExit.Update(mouseState);
// Press enter to play
if (keyboardState.IsKeyDown(Keys.Enter))
{
CreateNewGame();
currentGameState = GameState.playing;
}
}
Here's thee draw routine for main menu...
public void DrawMainMenu()
{
spriteBatch.Draw(mainMenuBackground, new Vector2(0, 0), Color.White);
buttonPlay.Draw(spriteBatch);
buttonExit.Draw(spriteBatch);
spriteBatch.DrawString(playerAmmoFont, String.Format("{0}", mouseState), new Vector2(0, 0), Color.White);
}
okay that's all I can think of
UPDATE - Okay so I know a few things that aren't the problem...
The whole of my button class is fine, I made a new project and inserted all the relevant code into it and it worked absolutely perfectly so I'm starting to think its something to do with the code positioning and the graphics device stuff although I still don't have a clue how to fix it.
the window appears at the same spot every time
there is no pattern to the change in coordinates at all
this is really annoying
UPDATE - OKAY. I spent a long time writing down the coordinates that I got each time I ran the code and stuck to cursor in the top right corner of the screen. Here is what I got.
(-203, -225)
(-253, -275)
(-53, -75)
(-103, -125)
(-153, -175)
(-203, -225)
(-253, -275)
(-53, -75)
(-103, -125)
(-153, -175)
(-203, -225)
(-253, -275)
(-53, -75)
(-103, -125)
(-153, -175)
(-203, -225)
(-253, -275)
(-53, -75)
(-103, -125)
(-153, -175)
(-203, -225)
(-78, -100)
(-128, -150)
(-178, -200)
(-228, -250)
(-28, -50)
(-53, -75)
(-103, -125)
(-153, -175) < AND FROM HERE THE PATTERN LOOPS ROUND.
I just don't get how the same code can execute a different bug on different executions like this.
Also, mouse.Wheel doesn't go up or down whereas it works on the project that I made to test the relevant code where the mouse position was relevant to the top left pixel of the game window.
UPDATE - EVEN MORE DAMN COMPLICATIONS - So I just rand it a few times again and the offset values are offset... the increase is the same but I got values like (-178, -200) then (-228, -250). I have also discovered that the mouse is not relative to the game window what so ever, if I jam the mouse in the top right corner of the screen and check the coordinates, then move the game window and do the same again, the coordinates don't change. Please please please help me, or tell me if I'm being stupid, or something. Thanks.
The mouse coordinates are relative to the monitor. Here is my general button class to try and work for your situation.
public class Button
{
public event EventHandler<EventArgs> Clicked;
public Vector2 Position { get; set;}
public Texture2D Texture { get; set;}
public Color Tint { get; set; }
public float Scale { get; set; }
public float Rotation { get; set; }
public int Width
{
get
{
if (texture == null)
return 0;
else
return texture.Width;
}
}
public int Height
{
get
{
if (texture == null)
return 0;
else
return texture.Height;
}
}
private void OnClick()
{
if (Clicked != null)
Clicked(this, EventArgs.Empty);
}
public Button(Vector2 position, Texture2D texture)
: base(parent)
{
Position = position;
Texture = texture;
Tint = Color.White;
Scale = 1.0f;
Rotation = 0.0f;
}
public bool HandleClick(Vector2 vector)
{
if (vector.X >= Position.X)
{
if (vector.X <= Position.X + Width)
{
if (vector.Y >= Position.Y)
{
if (vector.Y <= Position.Y + Height)
{
OnClick();
return true;
}
}
}
}
return false;
}
public bool HandleEntered(Vector2 vector)
{
if (vector.X >= Position.X)
{
if (vector.X <= Position.X + Width)
{
if (vector.Y >= Position.Y)
{
if (vector.Y <= Position.Y + Height)
{
return true;
}
}
}
}
return false;
}
public override void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, null, Tint, Rotation, Vector2.Zero, Scale, SpriteEffects.None, 0.0f);
}
Declare a button:
Button btn = new Button(position where you want the button, texture for the button);
btn.Clicked += () => { /* Handle button clicked code here */ };
In your update method inside your main game:
public void Update (GameTime gameTime)
{
MouseState mouseState = Mouse.GetState();
if(mouseState.LeftButton == ButtonState.Pressed) // check if mouse is clicked
{
btn.HandleClicked(new Vector2(mouseState.X, mouseState.Y)); // If true then the button clicked event will fire
// Here you can also change the color of the button if the button is currently clicked
}
// Here you can change the color of the button if the mouse is hover over the control
// Example:
btn.Tint = btn.HandleEntered(new Vector2(mouseState.X, mouseState.Y)) ? Color.White * 0.75f : Color.White;
}
Note: You can also use a rectangle for the button to adjust its size instead of strictly using the textures dimensions. Hope this gives some insight.
So here's what was going on: I had a bullet class in my game for every bullet shot. In this class I check whether the bullets hits nothing, hits the asteroid, or destroys the asteroids. If the latter is true then I would increment playerScore by 5. PlayerScore was a Game1 attribute so I thought the easiest way to do this would be to create a new Game1 in bullet.cs to allow me to refer to the variable. Deleting the "Main mainGame = new Main():" in Bullet.cs fixed this issue and I think the issue was coming from a new graphics device being made every single time I fired a single bullet.

How do I create a copy of this class and then use it's functions inside XNA (Gamedrawable Component)

using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
namespace TileEngine
{
class Renderer : DrawableGameComponent
{
SpriteBatch spriteBatch;
public Renderer(Game game)
: base(game)
{
// TODO: Construct any child components here
}
protected override void LoadContent()
{
// base.LoadContent();
}
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
public override void Initialize()
{
base.Initialize();
}
public RenderTarget2D new_texture(int width, int height)
{
Texture2D TEX = new Texture2D(GraphicsDevice, width, height); //create the texture to render to
RenderTarget2D Mine = new RenderTarget2D(GraphicsDevice, width, height);
GraphicsDevice.SetRenderTarget(Mine); //set the render device to the reference provided
//maybe base.draw can be used with spritebatch. Idk. We'll see if the order of operation
//works out. Wish I could call base.draw here.
return Mine; //I'm hoping that this returns the same instance and not a copy.
}
public void draw_texture(int width, int height, RenderTarget2D Mine)
{
GraphicsDevice.SetRenderTarget(null); //Set the renderer to render to the backbuffer again
Rectangle drawrect = new Rectangle(0, 0, width, height); //Set the rendering size to what we want
spriteBatch.Begin(); //This uses spritebatch to draw the texture directly to the screen
spriteBatch.Draw(Mine, drawrect, Color.White); //This uses the color white
spriteBatch.End(); //ends the spritebatch
//Call base.draw after this since it doesn't seem to recognize inside the function
//maybe base.draw can be used with spritebatch. Idk. We'll see if the order of operation
//works out. Wish I could call base.draw here.
}
public GraphicsDevice myDevice { get; set; }
}
}
I still can't call this class as an object in XNA
Here is the working code in the initialize function where I try to create it.
But in my draw code it still doesn't let me go:
tileclipping.draw_texture(...);
Here's the full code from game1
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;
using TileEngine;
namespace TileEngine
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
public GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
TileMap myMap = new TileMap();
int squaresAcross = 12;
int squaresDown = 12;
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()
{
// tileClipping = new Renderer();
// TODO: Add your initialization logic here
Renderer tileclipping = new Renderer(this) ;
//Components.Add(tileclippping);
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);
Tile.TileSetTexture = Content.Load<Texture2D>(#"Textures\TileSets\part1_tileset");
// 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();
KeyboardState ks = Keyboard.GetState();
if (ks.IsKeyDown(Keys.Left))
{
Camera.Location.X = MathHelper.Clamp(Camera.Location.X - 8, 0, (myMap.MapWidth - squaresAcross) * 32);
}
if (ks.IsKeyDown(Keys.Right))
{
Camera.Location.X = MathHelper.Clamp(Camera.Location.X + 8, 0, (myMap.MapWidth - squaresAcross) * 32);
}
if (ks.IsKeyDown(Keys.Up))
{
Camera.Location.Y = MathHelper.Clamp(Camera.Location.Y - 8, 0, (myMap.MapHeight - squaresDown) * 32);
}
if (ks.IsKeyDown(Keys.Down))
{
Camera.Location.Y = MathHelper.Clamp(Camera.Location.Y + 8, 0, (myMap.MapHeight - squaresDown) * 32);
}
// TODO: Add your update logic here
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);
//use the instance of renderer called tileclipping to generate a new texture of a specified size for tiles
//this surface is 200 pixels by 200 pixels for the reason that it's the same as the clipping i'll choose
Texture2D mytexture = new Texture2D(GraphicsDevice, 200, 200);
RenderTarget2D Mine = new RenderTarget2D(graphics.GraphicsDevice, 200, 200);
//Mine = tileclipping.new_texture(200, 200);
spriteBatch.Begin();
Vector2 firstSquare = new Vector2(Camera.Location.X / 32, Camera.Location.Y / 32);
int firstX = (int)firstSquare.X;
int firstY = (int)firstSquare.Y;
Vector2 squareOffset = new Vector2(Camera.Location.X % 32, Camera.Location.Y % 32);
int offsetX = (int)squareOffset.X;
int offsetY = (int)squareOffset.Y;
for (int y = 0; y < squaresDown; y++)
{
for (int x = 0; x < squaresAcross; x++)
{
spriteBatch.Draw(
Tile.TileSetTexture,
new Rectangle((x * 32) - offsetX, (y * 32) - offsetY, 32, 32),
Tile.GetSourceRectangle(myMap.Rows[y + firstY].Columns[x + firstX].TileID),
Color.White);
}
}
spriteBatch.End();
// TODO: Add your drawing code here
//There are two instances of mine
//A new one is made each time tileclipping.new_texture is called
//This function can re use the copy created by new texture
//hopefully this saves on memory
base.Draw(gameTime);
}
public CubeMapFace Tex2d { get; set; }
internal Renderer tileClipping { get; set; }
public IGameComponent tileclippping { get; set; }
}
}
I'm sorry if it isn't clear what i'm trying to do.
I'm trying to capture a 2d texture (or create one) OUTSIDE my game class
I'm trying to use a class as a handler, to pass these texture2d's back and forth between GAME1
and my Renderer
I don't WANT to have all my textures inside my main class.
Also another thing with this is that I'm trying to basically have a generic
texture2d CREATOR.
Aka this isn't for something simple like rendering sprites.
The function of RENDERER is to either create a new TEXTURE2D object with a NEW render target object
based on parameters fed to this function:
public RenderTarget2D new_texture(int width, int height)
{
Texture2D TEX = new Texture2D(GraphicsDevice, width, height); //create the texture to render to
RenderTarget2D Mine = new RenderTarget2D(GraphicsDevice, width, height);
GraphicsDevice.SetRenderTarget(Mine); //set the render device to the reference provided
//maybe base.draw can be used with spritebatch. Idk. We'll see if the order of operation
//works out. Wish I could call base.draw here.
return Mine; //I'm hoping that this returns the same instance and not a copy.
}
I need a way of creating a copy of the renderer class WITHOUT having it in the gamecomponents list.
The reason is because XNA won't let me access Graphics device, which is a required parameter OF a texture2D object.
So basically i'm doing all this stuff as a work around just becuase Texture2D requires graphics device as a parameter and I can't willy nilly pass GraphicsDevice INTO an instance of my renderer class i've already tried that and it fails.
So there will be situations in my game where say
if (Camera_zoom==1){
scaling_texture.dispose();
scaling_texture = tileclipping.new_texture(camera_width*camera_zoom, camera_height*camera_zoom);
// call a refresh command here
this.refresh_scene(...) //Inside here is a ton of sprite batches because the render target is now set to NEW scaling_texture
//after that we do the drawing using spritebatch inside draw function of main game class
//expecting that a render texture is provided for us by these pre requisites.
//then after that we call the render command
//it returns the render target to the screen
//then in the draw command AFTER the sprite batches were drawn TO the target surface called scaling_texture
//We use various parameters to tell it to draw this scaling_texture as a spritebatch.draw() inside the
//game1 draw class
//So basically I want to do things in this order
/// Create new texture of variable size
// use it as render target
// Do all my spritebatch
// call another spritebatch
//draw the contents of said texture on the screen as the rendering target
//Dispose of the texture object
//Check the scaling size of it
//Re create the scaling texture with a NEW resolution (each frame)
//Select it as a render target
//Do the spritebatchy stuff all over again repeat above for all game loop
//BUT I want parts of this, mainly the creation of this Texture2D object, and the drawing of it to the backbuffer
//To all happen inside my Renderer class
//but for all main game spritebatches to happen inside my main game class
//This is a problem for me and XNA doesn't seem to want to let me organize it this way
//Unless i'm missing something which is why i'm making this lengthy post
//ANY and all help is appreciated.
//Thanks again and I hope I explained myself well enough this time IE my intentions.
//PLEASE NOTE I am SET on doing things THIS way. I will NEED a texture 2d rendering target that is NON static
//During MOST of my GAME project.
//That said.. IT HAS TO have function to wrap it inside Renderer. THere is no way in hell I'm going to do this
//In a spaghetti code fashion Inside GAME1 with nested if statements.
//Thanks all
}
I just took the time to read it completely, and if I understand correctly, you want to have all your textures into a manager to be able to acess them from everywhere in your program ?
what I normally do is have a Class like this one :
Class Images
{
public static Texture2d Ball;
public static Texture2d Hero;
public static void loadContent(Content content)
{
Ball = content.load<Texture2d>("/GFX/GameObject/Ball");
Hero = content.load<Texture2d>("/GFX/SpriteSheet/Hero");
}
}
This class allow you to use Image.Hero or Image.Ball from everywhere in your code. All you have to do is to set it in your game loadcontent sub :
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
Images.LoadContent(GraphicsDeviceManager.Content);
Sounds.LoadContent(GraphicsDeviceManager.Content);
Tile.TileSetTexture = Content.Load<Texture2D>(#"Textures\TileSets\part1_tileset");
// TODO: use this.Content to load your game content here
}
From here, if you need to recreate or reload the texture in your own renderer class, you could set images.ball getter or setter differently and handle it how you want, or just create a new function to clone these texture and do what you need for your renderer class. Edit : I'm not 100% sure about if the class itself is static or not, I dont have the code in front of me and I didnt touch it in a long time.
I'm not home, so I cant find the tutorial I had about splash screen. but it also let you load a delegate instead of an asset, and that delegate lets you do some actions instead : as the 1st item to load, you load all the texture and fonts needed for your splash screen, as well as a background music that you start playing right away. If you want, let me know and I'll add in the link once I get home.

blackberry 5.0 api image mask/background image position

I've just started learning to develop blackberry apps and I've hit a bit of a snag. I'm unsure how I could move around a background image that is large than the field/manager it is being applied to. Here's an image to illustrate what I mean:
So far I have tried adding a Bitmap to a BitmapField inside a AbsolutePositionManager thinking I would be able to set the size of the absolute manager and just move the bitmapfield around inside it. That isn't the case, the manage just takes the size of the content inside it :(
I come from a frontend web dev background so what I'm looking for is something that behaves similar to the 'background-position' attribute in css or some sort of image mask.
Thanks in advance!
-- update --
This is a code sample of where I have got to. I now have a custom sized manager that displays a chunk of a larger BitmapField. I just need a way to move that BitmapField around.
package mypackage;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.container.AbsoluteFieldManager;
public class MyImage extends AbsoluteFieldManager {
protected void sublayout(int maxWidth, int maxHeight){
int displayWidth = 326;
int displayHeight = 79;
super.sublayout(displayWidth, displayHeight);
setExtent(displayWidth, displayHeight);
}
public MyImage(){
Bitmap _image = Bitmap.getBitmapResource("img.jpg");
BitmapField image = new BitmapField(_image);
add(image);
}
}
Rather than adding it as a Field, just store a reference to it somewhere in your Manager and then paint it yourself. Here's an untested example:
public class MyManager extends VerticalFieldManager() {
Bitmap _bg;
public MyManager() {
_bg = Bitmap.getBitmapResource("img.jpg");
}
protected void paint(Graphics graphics) {
graphics.drawBitmap(x_offset, y_offset, _bg.getWidth(), _bg.getHeight(), _bg, 0, 0);
super.paint(graphics);
}
}
Now you can just set x_offset and y_offset to whatever you want and it'll be shifted. If you need to mess with the size of the Manager to fit the Bitmap, add:
protected void sublayout(int width, int height) {
super.sublayout(width, height);
setExtent(Math.min(width, Math.max(getWidth(), _bg.getWidth())), Math.min(height, Math.max(getHeight(), _bg.getHeight()));
}
Hope this helps!

Resources