Pinch Zoom images bound in Listbox - windows-phone-7.1

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>

Related

Control Positioning of AdMob Banner in iOS via libGDX/RoboVM

I created my libGDX iOS project and I'm trying to position my AdMob ads to the bottom center of the screen but have no idea how to accomplish this. I'm using the bindings via RoboVM and do not know any of the RoboVM methods to control my ads. I copied the tutorial from here Does anyone have any tips or tutorials to help me accomplish this? Right now the ad seems to me missing 1/4 of whole banner ad is more towards the right of the screen. Below is my code:
public class IOSLauncher extends IOSApplication.Delegate implements IActivityRequestHandler{
private static final Logger log = new Logger(IOSLauncher.class.getName(), Application.LOG_DEBUG);
private static final boolean USE_TEST_DEVICES = true;
private GADBannerView adview;
private boolean adsInitialized = false;
private IOSApplication iosApplication;
#Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
config.orientationLandscape = true;
config.orientationPortrait = false;
iosApplication = new IOSApplication(new TestProject(this), config);
return iosApplication;
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
#Override
public void hide() {
initializeAds();
final CGSize screenSize = UIScreen.getMainScreen().getBounds().size();
double screenWidth = screenSize.width();
final CGSize adSize = adview.getBounds().size();
double adWidth = adSize.width();
double adHeight = adSize.height();
log.debug(String.format("Hidding ad. size[%s, %s]", adWidth, adHeight));
float bannerWidth = (float) screenWidth;
float bannerHeight = (float) (bannerWidth / adWidth * adHeight);
adview.setFrame(new CGRect(0, -bannerHeight, bannerWidth, bannerHeight));
}
#Override
public void show() {
initializeAds();
final CGSize screenSize = UIScreen.getMainScreen().getBounds().size();
double screenWidth = screenSize.width();
final CGSize adSize = adview.getBounds().size();
double adWidth = adSize.width();
double adHeight = adSize.height();
log.debug(String.format("Showing ad. size[%s, %s]", adWidth, adHeight));
float bannerWidth = (float) screenWidth;
float bannerHeight = (float) (bannerWidth / adWidth * adHeight);
adview.setFrame(new CGRect((screenWidth / 2) - adWidth / 2, 0, bannerWidth, bannerHeight));
}
public void initializeAds() {
if (!adsInitialized) {
log.debug("Initalizing ads...");
adsInitialized = true;
adview = new GADBannerView(GADAdSize.banner());
adview.setAdUnitID(Constants.AdUnitID); //put your secret key here
adview.setRootViewController(iosApplication.getUIViewController());
iosApplication.getUIViewController().getView().addSubview(adview);
final GADRequest request = GADRequest.create();
adview.setDelegate(new GADBannerViewDelegateAdapter() {
#Override
public void didReceiveAd(GADBannerView view) {
super.didReceiveAd(view);
log.debug("didReceiveAd");
}
#Override
public void didFailToReceiveAd(GADBannerView view,
GADRequestError error) {
super.didFailToReceiveAd(view, error);
log.debug("didFailToReceiveAd:" + error);
}
});
adview.loadRequest(request);
log.debug("Initalizing ads complete.");
}
}
#Override
public void showAds(boolean show) {
initializeAds();
final CGSize screenSize = UIScreen.getMainScreen().getBounds().size();
double screenWidth = screenSize.width();
final CGSize adSize = adview.getBounds().size();
double adWidth = adSize.width();
double adHeight = adSize.height();
log.debug(String.format("Hidding ad. size[%s, %s]", adWidth, adHeight));
float bannerWidth = (float) screenWidth;
float bannerHeight = (float) (bannerWidth / adWidth * adHeight);
if(show) {
adview.setFrame(new CGRect((screenWidth / 2) - adWidth / 2, 0, bannerWidth, bannerHeight));
} else {
adview.setFrame(new CGRect(0, -bannerHeight, bannerWidth, bannerHeight));
}
you set the ad position with
adview.setFrame(CGRect);
if you inspect the parameters of CGRect it's like;
CGRect(double x, double y, double width, double height)
0,0 coordinates (x,y) is top left. so, your code;
// center of screen
double adX = (screenWidth / 2) - (adWidth / 2);
// bottom of screen
double adY = screenHeight - bannerHeight;
adview.setFrame(new CGRect(adX, adY, bannerWidth, bannerHeight));
and the other important thing, you should not manipulate the positioning in two method! your showAds method should be like;
public void showAds(boolean show) {
if (show) {
show();
} else {
hide();
}
}

how to animate diff images in xna game?

i am having 19 images , which are animation frames of my player
in below i have created array of texture as frog which is my player.and there are 19 images.how to animate them.
public class Texture
{
public static Texture2D mBackground;
public static Texture2D mBackgroundOne;
public static Texture2D mBackgroundTwo;
public static Texture2D grassUp;
public static Texture2D grassDown;
public static Texture2D[] frog = new Texture2D[19];
public static Texture2D[] frogdie = new Texture2D[4];
public static Vector2 position;
public static void Load()
{
mBackground = GamePage.contentManager.Load<Texture2D>("layer_11");
mBackgroundOne = GamePage.contentManager.Load<Texture2D>("layer_11");
mBackgroundTwo = GamePage.contentManager.Load<Texture2D>("layer_11");
grassUp = GamePage.contentManager.Load<Texture2D>("layer_11");
grassDown = GamePage.contentManager.Load<Texture2D>("layer_11");
frog[0] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal1");
frog[1] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal2");
frog[2] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal3");
frog[3] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal4");
frog[4] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal5");
frog[5] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal6");
frog[6] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal7");
frog[7] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal8");
frog[8] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal9");
frog[9] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal10");
frog[10] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal11");
frog[11] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal12");
frog[12] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal13");
frog[13] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal14");
frog[14] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal15");
frog[15] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal16");
frog[16] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal17");
frog[17] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal18");
frog[18] = GamePage.contentManager.Load<Texture2D>("player/maindak_normal19");
}
public static void draw(SpriteBatch sprite)
{
for (int i = 0; i <= 18; i++)
{
sprite.Draw(frog[i],position= new Vector2(100, 100), Color.White);
}
}
Keeping with your current structure, you could animate your textures in the following manner:
//timer
private const float TIME_BETWEEN_FRAME = 0.1f;
private float timer = TIME_BETWEEN_FRAME;
//frame sequence
private int currentFrame = 0;
public void Update(GameTime gametime)
{
float elapsed = (float)gametime.ElapsedGameTime.TotalSeconds;
timer -= elapsed; //subtract elapsed time from timer
if (timer <= 0) //if our timer is elapsed
{
currentFrame++; //next frame
if (currentFrame >= frog.Count)
currentFrame = 0; //If we reach last frame, reset to loop
timer = TIME_BETWEEN_FRAME; //reset timer
}
}
public void draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(frog[currentFrame], position, Color.White);
}
This will work, however, if you want to take it a step further into the right direction, you should look into SpriteSheets, which will provide you with a much easier way to manage all of your animations.

XNA Can't create multiple instances?

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?

How to avoid mixing different sprite animation speed?

I dun know why each time I call Update_Animation(Point sheetSize, TimeSpan frameInterval, GameTime gameTime) function, the sprite animation speed becomes more faster. Does it causes by gameTime? How to fix it? Thanks.
class Character
{
#region Field
// Character file
System.Xml.Linq.XDocument doc;
// The texture with animation frames
Texture2D animationTexture_Stand;
Texture2D animationTexture_Run;
Texture2D animationTexture_Hit;
// The size of single frame inside the animationTexture
public Point frameSize_Stand;
public Point frameSize_Run;
public Point frameSize_Hit;
// The size and structure of whole frames sheet in animationTexture. The animationTexture could
// hold animaton sequence organized in multiple rows and multiple columns.
Point sheetSize_Stand;
Point sheetSize_Run;
Point sheetSize_Hit;
// Amount of time between frames
TimeSpan frameInterval_Stand;
TimeSpan frameInterval_Run;
TimeSpan frameInterval_Hit;
#endregion
#region Initialization
/// <summary>
/// Constructor of a character class
/// </summary>
/// <param name="characterName">the name of the xml file of the character without .xml</param>
/// <param name="content">ContentManager instance</param>
public Character(String characterName, ContentManager content)
{
doc = System.Xml.Linq.XDocument.Load("Content/" + "Player/" + characterName + ".xml");
// Get the first sprite info from the XML definition
var stand = doc.Root.Element("stand");
var run = doc.Root.Element("run");
var hit = doc.Root.Element("hit");
animationTexture_Stand = content.Load<Texture2D>(stand.Attribute("SheetName").Value);
animationTexture_Run = content.Load<Texture2D>(run.Attribute("SheetName").Value);
animationTexture_Hit = content.Load<Texture2D>(hit.Attribute("SheetName").Value);
frameSize_Stand = new Point();
frameSize_Stand.X = int.Parse(stand.Attribute("FrameWidth").Value, NumberStyles.Integer);
frameSize_Stand.Y = int.Parse(stand.Attribute("FrameHeight").Value, NumberStyles.Integer);
frameSize_Run = new Point();
frameSize_Run.X = int.Parse(run.Attribute("FrameWidth").Value, NumberStyles.Integer);
frameSize_Run.Y = int.Parse(run.Attribute("FrameHeight").Value, NumberStyles.Integer);
frameSize_Hit = new Point();
frameSize_Hit.X = int.Parse(hit.Attribute("FrameWidth").Value, NumberStyles.Integer);
frameSize_Hit.Y = int.Parse(hit.Attribute("FrameHeight").Value, NumberStyles.Integer);
sheetSize_Stand = new Point();
sheetSize_Stand.X = int.Parse(stand.Attribute("SheetColumns").Value, NumberStyles.Integer);
sheetSize_Stand.Y = int.Parse(stand.Attribute("SheetRows").Value, NumberStyles.Integer);
sheetSize_Run = new Point();
sheetSize_Run.X = int.Parse(run.Attribute("SheetColumns").Value, NumberStyles.Integer);
sheetSize_Run.Y = int.Parse(run.Attribute("SheetRows").Value, NumberStyles.Integer);
sheetSize_Hit = new Point();
sheetSize_Hit.X = int.Parse(hit.Attribute("SheetColumns").Value, NumberStyles.Integer);
sheetSize_Hit.Y = int.Parse(hit.Attribute("SheetRows").Value, NumberStyles.Integer);
frameInterval_Stand = TimeSpan.FromSeconds(1.0f / int.Parse(stand.Attribute("Speed").Value, NumberStyles.Integer));
frameInterval_Run = TimeSpan.FromSeconds(1.0f / int.Parse(run.Attribute("Speed").Value, NumberStyles.Integer));
frameInterval_Hit = TimeSpan.FromSeconds(1.0f / int.Parse(hit.Attribute("Speed").Value, NumberStyles.Integer));
}
#endregion
#region Update Animation
TimeSpan nextFrame;
Point currentFrame;
public void Update_Animation(Point sheetSize, TimeSpan frameInterval, GameTime gameTime)
{
if (nextFrame >= frameInterval)
{
currentFrame.X++;
if (currentFrame.X >= sheetSize.X)
{
currentFrame.X = 0;
currentFrame.Y++;
}
if (currentFrame.Y >= sheetSize.Y)
currentFrame.Y = 0;
nextFrame = TimeSpan.Zero;
}
else
{
nextFrame += gameTime.ElapsedGameTime;
}
}
#endregion
#region Update Control
KeyboardState mPreviousKeyboardState;
String action;
SpriteEffects effect = SpriteEffects.FlipHorizontally;
Vector2 feetPosition = new Vector2(0, 450);
Vector2 mSpeed = Vector2.Zero;
Vector2 mDirection = Vector2.Zero;
Vector2 mStartingPosition = Vector2.Zero;
int CHARACTER_SPEED = 50;
int MOVE_LEFT = -5;
int MOVE_RIGHT = 5;
int MOVE_UP = -5;
int MOVE_DOWN = 5;
enum State
{
Walking,
Jumping,
Hitting,
}
State mCurrentState = State.Walking;
public void UpdateControl(GameTime gameTime)
{
KeyboardState aCurrentKeyboardState = Keyboard.GetState();
feetPosition += mDirection * mSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
UpdateMovement(aCurrentKeyboardState, gameTime);
UpdateJump(aCurrentKeyboardState, gameTime);
mPreviousKeyboardState = aCurrentKeyboardState;
}
private void UpdateMovement(KeyboardState aCurrentKeyboardState, GameTime gameTime)
{
if (mCurrentState == State.Walking)
{
action = "stand";
Update_Animation(sheetSize_Stand, frameInterval_Stand, gameTime);
mSpeed = Vector2.Zero;
mDirection = Vector2.Zero;
if (aCurrentKeyboardState.IsKeyDown(Keys.Left) && !aCurrentKeyboardState.IsKeyDown(Keys.Right))
{
action = "run";
effect = SpriteEffects.None;
mSpeed.X = CHARACTER_SPEED;
mDirection.X = MOVE_LEFT;
Update_Animation(sheetSize_Run, frameInterval_Run, gameTime);
}
else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) && !aCurrentKeyboardState.IsKeyDown(Keys.Left))
{
action = "run";
effect = SpriteEffects.FlipHorizontally;
mSpeed.X = CHARACTER_SPEED;
mDirection.X = MOVE_RIGHT;
Update_Animation(sheetSize_Run, frameInterval_Run, gameTime);
}
if (aCurrentKeyboardState.IsKeyDown(Keys.Z) && mPreviousKeyboardState.IsKeyUp(Keys.Z))
{
mCurrentState = State.Hitting;
}
}
if (mCurrentState == State.Hitting)
{
action = "hit";
Update_Animation(sheetSize_Hit, frameInterval_Hit, gameTime);
mCurrentState = State.Walking;
}
}
private void UpdateJump(KeyboardState aCurrentKeyboardState, GameTime gameTime)
{
if (mCurrentState == State.Walking)
{
if (aCurrentKeyboardState.IsKeyDown(Keys.Up) && mPreviousKeyboardState.IsKeyUp(Keys.Up))
Jump();
}
if (mCurrentState == State.Jumping)
{
if (mStartingPosition.Y - feetPosition.Y > 150)
mDirection.Y = MOVE_DOWN;
if (feetPosition.Y > mStartingPosition.Y)
{
feetPosition.Y = mStartingPosition.Y;
mCurrentState = State.Walking;
mDirection = Vector2.Zero;
}
}
}
private void Jump()
{
if (mCurrentState != State.Jumping)
{
mCurrentState = State.Jumping;
mStartingPosition = feetPosition;
mDirection.Y = MOVE_UP;
mSpeed = new Vector2(CHARACTER_SPEED, CHARACTER_SPEED);
}
}
#endregion
#region Draw Animation
Texture2D animationTexture;
Point frameSize;
/// <summary>
/// Rendering of the animation
/// </summary>
/// <param name="spriteBatch">SpriteBatch in which current frame will be rendered</param>
/// <param name="position">The position of the current frame</param>
/// <param name="scale">Scale factor to apply on the current frame</param>
/// <param name="spriteEffect">SpriteEffect to apply on the current frame</param>
public void Draw_Animation(SpriteBatch spriteBatch)
{
if (action == "stand")
{
Assign_Sprite(animationTexture_Stand, frameSize_Stand);
Draw_Action(spriteBatch, feetPosition, 1.0f, effect);
}
else if (action == "run")
{
Assign_Sprite(animationTexture_Run, frameSize_Run);
Draw_Action(spriteBatch, feetPosition, 1.0f, effect);
}
else if (action == "hit")
{
Assign_Sprite(animationTexture_Hit, frameSize_Hit);
Draw_Action(spriteBatch, feetPosition, 1.0f, effect);
}
}
private void Assign_Sprite(Texture2D assignAnimationTexture, Point assignFrameSize)
{
animationTexture = assignAnimationTexture;
//currentFrame = AssignCurrentFrame;
frameSize = assignFrameSize;
}
private void Draw_Action(SpriteBatch spriteBatch, Vector2 position, float scale, SpriteEffects spriteEffect)
{
spriteBatch.Draw(animationTexture, position - new Vector2(0, frameSize.Y), new Rectangle(
frameSize.X * currentFrame.X,
frameSize.Y * currentFrame.Y,
frameSize.X,
frameSize.Y),
Color.White, 0f, Vector2.Zero, scale, spriteEffect, 0);
}
#endregion
}
I'm not sure if that is the problem, but this code concerns me:
if (nextFrame >= frameInterval)
{
//Blah blah
nextFrame = TimeSpan.Zero;
}
If gameTime.ElapsedGameTime is not regular (if your game is having performance problems), this method will not be correctly timed. Instead, you should try:
while (nextFrame >= frameInterval)
{
//Blah blah
nextFrame -= frameInterval;
}
Thus there will be some time "left over" in nextFrame, so the next animation will come at the right time.
However, since your question isn't very clear, I'm not sure if this will actually fix your problem.

Find closest airport based on latitude and longitude

How do I find closest airport using longitude and latitude ?
Any specific web services and any database to achieve ?
One WebService I found is airports.pidgets.com
This is an example:
XML format
http://airports.pidgets.com/v1/airports?near=45.3515,9.3753
JSon format
http://airports.pidgets.com/v1/airports?near=45.3515,9.3753&format=json
[Edit]
Found another webservice on aviationweather.gov (only XML and CSV)
http://aviationweather.gov/adds/dataserver_current/httpparam?dataSource=stations&requestType=retrieve&format=xml&radialDistance=20;9.3753,45.3515
From both sites you can download a "static" airports list, to perform offline search.
Regards
You need a dataset with fields for the airport`s latitude and
longitude
Use the calculation for Great-Circle distance (GCD) as outlined on the page linked below
Wikipedia article on GCD
Please provide example code/specify the language if you would like further and more specific help
CODE:
Taken from another webpage (now defunct, used waybackmachine)
using System;
namespace HaversineFormula
{
/// <summary>
/// The distance type to return the results in.
/// </summary>
public enum DistanceType { Miles, Kilometers };
/// <summary>
/// Specifies a Latitude / Longitude point.
/// </summary>
public struct Position
{
public double Latitude;
public double Longitude;
}
class Haversine
{
/// <summary>
/// Returns the distance in miles or kilometers of any two
/// latitude / longitude points.
/// </summary>
/// <param name=”pos1″></param>
/// <param name=”pos2″></param>
/// <param name=”type”></param>
/// <returns></returns>
public double Distance(Position pos1, Position pos2, DistanceType type)
{
double R = (type == DistanceType.Miles) ? 3960 : 6371;
double dLat = this.toRadian(pos2.Latitude - pos1.Latitude);
double dLon = this.toRadian(pos2.Longitude - pos1.Longitude);
double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Cos(this.toRadian(pos1.Latitude)) * Math.Cos(this.toRadian(pos2.Latitude)) *
Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
double d = R * c;
return d;
}
/// <summary>
/// Convert to Radians.
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
private double toRadian(double val)
{
return (Math.PI / 180) * val;
}
}
}
Pseudocode:
This pseudocode should give you the answer you are looking for. I didn't test this and the C# will probably have syntactic errors but the gist of it should be clear.
/* Set parameters */
Position currentPosition = new Position();
Position airportPosition = new Position();
Double minDistance = Double.MaxValue;
String closestAirportName = "UNKNOWN";
Haversine hv = new Haversine();
/* Set current position, remains fixed throughout */
currentPosition.Latitude = 0.000;
currentPosition.Longitude = 0.000;
/* Compare distance to each airport with current location
* and save results if this is the closest airport so far*/
Foreach (airport in airports) {
airportPosition = new Position(airport.Lat, airport.Lon);
Double distanceToAirport = hv.Distance(currentPosition, airportPosition, DistanceType.Kilometers)
if (distanceToAirport < minDistance) {
minDistance = distanceToAirport
closestAirportName = airport.Name
}
}
On which platform are you coding, Durga? Is it Android?
In this case, you could use the Google Maps API:
https://developers.google.com/maps/
and, in particular, Google Places:
https://developers.google.com/places/
Broswe their documentation for details. In particular, check their license.
this.nearestAirport = this.airports.find((airport) => {
return (Math.round(airport.latitude) === Math.round(currentLocation.latitude) &&
Math.round(airport.longitude) === Math.round(currentLocation.longitude));
});
To Find nearest airport and to get directions to reach there from a specified point (Lat,Lan)
Here is a Google method,without any database to achieve this :
onclick="getNeighbourhood('<%= propLat %>','<%= propLan %>');"
For full code visit here FULL NEAREST AIRPORT SCRIPT AND STYLE
function getNeighbourhood(propLatQ,propLanQ) {
propLat=propLatQ;
propLan=propLanQ;
var myLatlng = new google.maps.LatLng(propLat,propLan);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
places = new google.maps.places.PlacesService(map);
google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);
autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
google.maps.event.addListener(autocomplete, 'place_changed', function() {
showSelectedPlace();
});

Resources