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?
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 am testing UNET (Unity 5.2) but is running into problem with things that probably should be very simple.
I have an Orange fruit (GameObject) that i can drag and have attached the network transform in code. When releasing the mouse (Mouse Up) I want to release the ownership of the Orange so none owns it, want later to attach to another player. I have tested with ReplacePlayerForConnection and a few other things but totally screwed up the code.
I have now reset everything and must ask for some help how to do this.
The scripts i have, attached to the Orange GameObject, is:
1
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class orange : NetworkBehaviour {
float distance = 10;
void Start() {
if (isLocalPlayer) {
//GameObject.Find("Main Camera").SetActive(false);
}
}
void OnMouseDrag() {
Vector3 mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, distance);
Vector3 objPosition = Camera.main.ScreenToWorldPoint (mousePosition);
transform.position = objPosition;
}
void OnMouseUp() {
print (">>> MOUSE UP <<<");
if (isLocalPlayer) {
GetComponent<NetworkIdentity> ().localPlayerAuthority = false;
GetComponent<NetworkIdentity> ().serverOnly = false;
}
}
Here is scrip #2 attached to the Orange GameObject:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class Orange_SyncPosition : NetworkBehaviour {
[SyncVar] // Server will automatically transmit this value to all players when it changes
private Vector3 syncPos;
[SerializeField] Transform myTransform;
[SerializeField] float lerpRate = 15;
void FixedUpdate () {
TransmitPosition ();
LerpPosition ();
}
void LerpPosition() {
if (!isLocalPlayer) {
myTransform.position = Vector3.Lerp(myTransform.position, syncPos, Time.deltaTime *lerpRate);
}
}
[Command]
void CmdProvidePositionToServer (Vector3 pos) {
syncPos = pos;
}
[ClientCallback]
void TransmitPosition () {
if (isLocalPlayer) {
CmdProvidePositionToServer (myTransform.position);
}
}
}
Use NetworkServer.ReplacePlayerForConnection():
// Player is a NetworkBehaviour on the existing player object
void ReplacePlayer (Player existingPlayer) {
var conn = existingPlayer.connectionToClient;
var newPlayer = Instantiate<GameObject>(playerPrefab);
Destroy(existingPlayer.gameObject);
NetworkServer.ReplacePlayerForConnection(conn, newPlayer, 0);
}
Use AssignClientAuthority / RemoveClientAuthority
And never touch these parameters at runtime:
GetComponent<NetworkIdentity> ().localPlayerAuthority = false;
GetComponent<NetworkIdentity> ().serverOnly = false;
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));
...
}
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.
I am trying to implement pinch zoom in my application. I found this article (Correct Pinch-Zoom in Silverlight) and it works perfectly fine for one image. But the problem is, my images are within listbox as shown in below XAML:
<ListBox x:Name="lstImage" Margin="-20,-23,-12,32" Height="709" Width="480">
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Path=ImageSource}" VerticalAlignment="Top" Margin="10,12,10,10" Width="640" Height="800">
</Image>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I am not able to understand how to implement that solution. Thanks in advance.
Create a class with name PinchZomBehavior.cs and add the following code.
public class PinchZomBehavior : Behavior<Image>
{
private double _totalImageScale = 1d;
private Point _imagePosition = new Point(0, 0);
private const double MaxImageZoom = 5;
private Point _oldFinger1;
private Point _oldFinger2;
private double _oldScaleFactor;
private Image _imgZoom;
protected override void OnAttached()
{
_imgZoom = AssociatedObject;
_imgZoom.RenderTransform = new CompositeTransform { ScaleX = 1, ScaleY = 1, TranslateX = 0, TranslateY = 0 };
var listener = GestureService.GetGestureListener(AssociatedObject);
listener.PinchStarted += OnPinchStarted;
listener.PinchDelta += OnPinchDelta;
listener.DragDelta += OnDragDelta;
listener.DoubleTap += OnDoubleTap;
base.OnAttached();
}
#region Pinch and Zoom Logic
#region Event handlers
/// <summary>
/// Initializes the zooming operation
/// </summary>
private void OnPinchStarted(object sender, PinchStartedGestureEventArgs e)
{
_oldFinger1 = e.GetPosition(_imgZoom, 0);
_oldFinger2 = e.GetPosition(_imgZoom, 1);
_oldScaleFactor = 1;
}
/// <summary>
/// Computes the scaling and translation to correctly zoom around your fingers.
/// </summary>
private void OnPinchDelta(object sender, PinchGestureEventArgs e)
{
var scaleFactor = e.DistanceRatio / _oldScaleFactor;
if (!IsScaleValid(scaleFactor))
return;
var currentFinger1 = e.GetPosition(_imgZoom, 0);
var currentFinger2 = e.GetPosition(_imgZoom, 1);
var translationDelta = GetTranslationDelta(
currentFinger1,
currentFinger2,
_oldFinger1,
_oldFinger2,
_imagePosition,
scaleFactor);
_oldFinger1 = currentFinger1;
_oldFinger2 = currentFinger2;
_oldScaleFactor = e.DistanceRatio;
UpdateImageScale(scaleFactor);
UpdateImagePosition(translationDelta);
}
/// <summary>
/// Moves the image around following your finger.
/// </summary>
private void OnDragDelta(object sender, DragDeltaGestureEventArgs e)
{
var translationDelta = new Point(e.HorizontalChange, e.VerticalChange);
if (IsDragValid(1, translationDelta))
UpdateImagePosition(translationDelta);
}
/// <summary>
/// Resets the image scaling and position
/// </summary>
private void OnDoubleTap(object sender, GestureEventArgs e)
{
ResetImagePosition();
}
#endregion
#region Utils
/// <summary>
/// Computes the translation needed to keep the image centered between your fingers.
/// </summary>
private Point GetTranslationDelta(
Point currentFinger1, Point currentFinger2,
Point oldFinger1, Point oldFinger2,
Point currentPosition, double scaleFactor)
{
var newPos1 = new Point(
currentFinger1.X + (currentPosition.X - oldFinger1.X) * scaleFactor,
currentFinger1.Y + (currentPosition.Y - oldFinger1.Y) * scaleFactor);
var newPos2 = new Point(
currentFinger2.X + (currentPosition.X - oldFinger2.X) * scaleFactor,
currentFinger2.Y + (currentPosition.Y - oldFinger2.Y) * scaleFactor);
var newPos = new Point(
(newPos1.X + newPos2.X) / 2,
(newPos1.Y + newPos2.Y) / 2);
return new Point(
newPos.X - currentPosition.X,
newPos.Y - currentPosition.Y);
}
/// <summary>
/// Updates the scaling factor by multiplying the delta.
/// </summary>
private void UpdateImageScale(double scaleFactor)
{
_totalImageScale *= scaleFactor;
ApplyScale();
}
/// <summary>
/// Applies the computed scale to the image control.
/// </summary>
private void ApplyScale()
{
((CompositeTransform)_imgZoom.RenderTransform).ScaleX = _totalImageScale;
((CompositeTransform)_imgZoom.RenderTransform).ScaleY = _totalImageScale;
}
/// <summary>
/// Updates the image position by applying the delta.
/// Checks that the image does not leave empty space around its edges.
/// </summary>
private void UpdateImagePosition(Point delta)
{
var newPosition = new Point(_imagePosition.X + delta.X, _imagePosition.Y + delta.Y);
if (newPosition.X > 0) newPosition.X = 0;
if (newPosition.Y > 0) newPosition.Y = 0;
if ((_imgZoom.ActualWidth * _totalImageScale) + newPosition.X < _imgZoom.ActualWidth)
newPosition.X = _imgZoom.ActualWidth - (_imgZoom.ActualWidth * _totalImageScale);
if ((_imgZoom.ActualHeight * _totalImageScale) + newPosition.Y < _imgZoom.ActualHeight)
newPosition.Y = _imgZoom.ActualHeight - (_imgZoom.ActualHeight * _totalImageScale);
_imagePosition = newPosition;
ApplyPosition();
}
/// <summary>
/// Applies the computed position to the image control.
/// </summary>
private void ApplyPosition()
{
((CompositeTransform)_imgZoom.RenderTransform).TranslateX = _imagePosition.X;
((CompositeTransform)_imgZoom.RenderTransform).TranslateY = _imagePosition.Y;
}
/// <summary>
/// Resets the zoom to its original scale and position
/// </summary>
private void ResetImagePosition()
{
_totalImageScale = 1;
_imagePosition = new Point(0, 0);
ApplyScale();
ApplyPosition();
}
/// <summary>
/// Checks that dragging by the given amount won't result in empty space around the image
/// </summary>
private bool IsDragValid(double scaleDelta, Point translateDelta)
{
if (_imagePosition.X + translateDelta.X > 0 || _imagePosition.Y + translateDelta.Y > 0)
return false;
if ((_imgZoom.ActualWidth * _totalImageScale * scaleDelta) + (_imagePosition.X + translateDelta.X) < _imgZoom.ActualWidth)
return false;
if ((_imgZoom.ActualHeight * _totalImageScale * scaleDelta) + (_imagePosition.Y + translateDelta.Y) < _imgZoom.ActualHeight)
return false;
return true;
}
/// <summary>
/// Tells if the scaling is inside the desired range
/// </summary>
private bool IsScaleValid(double scaleDelta)
{
return (_totalImageScale * scaleDelta >= 1) && (_totalImageScale * scaleDelta <= MaxImageZoom);
}
#endregion
#endregion
}
And attach the behavior to image control like this
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<Image Stretch="Uniform" Source="{Binding Image}" CacheMode="BitmapCache">
<i:Interaction.Behaviors>
<Behaviors:PinchZomBehavior/>
</i:Interaction.Behaviors>
</Image>