i create a new project in visual studio 2017 in monogame windows platform and when i double click on.
in content mgcb i load png file for example and click build and nothing happening i don't get error or see something move.
why this happening?
i try to load 4 files:
crosshairs
galleryFont
sky
target
visual studio code:
namespace shooter_gallery
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
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
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
}
thanks
Related
I'm working through this tutorial: https://mtaulty.com/2019/07/18/simple-shared-holograms-with-photon-networking-part-1/ with the hope of reproducing the shared coordinate system between two Hololens 2 headsets. I'm using Unity 2020, PUN2, ARFoundation and MRTK.
Because the tutorial is using WorldAnchors (WSA platform), which is a bit old, I'm trying to modify it to use ARFoundation. So far, the code I have as a result, seems to properly have the two headsets communicating via PUN2, but the blue cube as shown in the tutorial does not align between the headsets. The cube simply seems referenced to each headsets initial startup frame of reference. Below is the code. I've kept everything as one-to-one with the tutorial as possible, except where I felt I needed to swap WorldAnchors for ARAnchors and also where I swapped in a SpatialAnchorManager class to handle the Azure Spatial Service session since I found the tutorial's StartSession function didn't seem to work properly. Both AzureSpatialAnchorService.cs and PhotonScript.cs are attached to a root game object in the scene. Picture of the scene attached. Based on the debug logs I'm able to tell that the first headset is creating and saving an anchor to Azure and the second headset is able to find that same anchor. But I apparently am not performing a necessary transformation between headsets?
Can anyone suggest what I'm doing wrong and/or what specific edits that need to be made to get spatial alignment between headsets?
Thanks!
AzureSpatialAnchorService.cs:
using Microsoft.Azure.SpatialAnchors.Unity;
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.WSA;
namespace AzureSpatialAnchors
{
[RequireComponent(typeof(SpatialAnchorManager))]
public class AzureSpatialAnchorService : MonoBehaviour
{
[Serializable]
public class AzureSpatialAnchorServiceProfile
{
[SerializeField]
[Tooltip("The account id from the Azure portal for the Azure Spatial Anchors service")]
string azureAccountId;
public string AzureAccountId => this.azureAccountId;
[SerializeField]
[Tooltip("The access key from the Azure portal for the Azure Spatial Anchors service (for Key authentication)")]
string azureServiceKey;
public string AzureServiceKey => this.azureServiceKey;
}
[SerializeField]
[Tooltip("The configuration for the Azure Spatial Anchors Service")]
AzureSpatialAnchorServiceProfile profile = new AzureSpatialAnchorServiceProfile();
public AzureSpatialAnchorServiceProfile Profile => this.profile;
TaskCompletionSource<CloudSpatialAnchor> taskWaitForAnchorLocation;
//CloudSpatialAnchorSession cloudSpatialAnchorSession;
private SpatialAnchorManager _spatialAnchorManager = null;
public AzureSpatialAnchorService()
{
}
public async Task<string> CreateAnchorOnObjectAsync(GameObject gameObjectForAnchor)
{
string anchorId = string.Empty;
try
{
await this.StartSession();
Debug.Log("Started Session");
//Add and configure ASA components
CloudNativeAnchor cloudNativeAnchor = gameObjectForAnchor.AddComponent<CloudNativeAnchor>();
await cloudNativeAnchor.NativeToCloud();
Debug.Log("After NativeToCloud");
CloudSpatialAnchor cloudSpatialAnchor = cloudNativeAnchor.CloudAnchor;
cloudSpatialAnchor.Expiration = DateTimeOffset.Now.AddDays(3);
// As per previous comment.
//Collect Environment Data
while (!_spatialAnchorManager.IsReadyForCreate)
{
float createProgress = _spatialAnchorManager.SessionStatus.RecommendedForCreateProgress;
Debug.Log($"ASA - Move your device to capture more environment data: {createProgress:0%}");
}
Debug.Log($"ASA - Saving room cloud anchor... ");
await _spatialAnchorManager.CreateAnchorAsync(cloudSpatialAnchor);
anchorId = cloudSpatialAnchor?.Identifier;
bool saveSucceeded = cloudSpatialAnchor != null;
if (!saveSucceeded)
{
Debug.LogError("ASA - Failed to save, but no exception was thrown.");
return anchorId;
}
anchorId = cloudSpatialAnchor.Identifier;
Debug.Log($"ASA - Saved room cloud anchor with ID: {anchorId}");
}
catch (Exception exception) // TODO: reasonable exceptions here.
{
Debug.Log("ASA - Failed to save room anchor: " + exception.ToString());
Debug.LogException(exception);
}
return (anchorId);
}
public async Task<bool> PopulateAnchorOnObjectAsync(string anchorId, GameObject gameObjectForAnchor)
{
bool anchorLocated = false;
try
{
await this.StartSession();
this.taskWaitForAnchorLocation = new TaskCompletionSource<CloudSpatialAnchor>();
var watcher = _spatialAnchorManager.Session.CreateWatcher(
new AnchorLocateCriteria()
{
Identifiers = new string[] { anchorId },
BypassCache = true,
Strategy = LocateStrategy.AnyStrategy,
RequestedCategories = AnchorDataCategory.Spatial
}
);
var cloudAnchor = await this.taskWaitForAnchorLocation.Task;
anchorLocated = cloudAnchor != null;
if (anchorLocated)
{
Debug.Log("Anchor located");
gameObjectForAnchor.AddComponent<CloudNativeAnchor>().CloudToNative(cloudAnchor);
Debug.Log("Attached Local Anchor");
}
watcher.Stop();
}
catch (Exception ex) // TODO: reasonable exceptions here.
{
Debug.Log($"Caught {ex.Message}");
}
return (anchorLocated);
}
/// <summary>
/// Start the Azure Spatial Anchor Service session
/// This must be called before calling create, populate or delete methods.
/// </summary>
public async Task<bool> StartSession()
{
//if (this.cloudSpatialAnchorSession == null)
//{
// Debug.Assert(this.cloudSpatialAnchorSession == null);
// this.ThrowOnBadAuthConfiguration();
// // setup the session
// this.cloudSpatialAnchorSession = new CloudSpatialAnchorSession();
// // set the Azure configuration parameters
// this.cloudSpatialAnchorSession.Configuration.AccountId = this.Profile.AzureAccountId;
// this.cloudSpatialAnchorSession.Configuration.AccountKey = this.Profile.AzureServiceKey;
// // register event handlers
// this.cloudSpatialAnchorSession.Error += this.OnCloudSessionError;
// this.cloudSpatialAnchorSession.AnchorLocated += OnAnchorLocated;
// this.cloudSpatialAnchorSession.LocateAnchorsCompleted += OnLocateAnchorsCompleted;
// // start the session
// this.cloudSpatialAnchorSession.Start();
//}
_spatialAnchorManager = GetComponent<SpatialAnchorManager>();
_spatialAnchorManager.LogDebug += (sender, args) => Debug.Log($"ASA - Debug: {args.Message}");
_spatialAnchorManager.Error += (sender, args) => Debug.LogError($"ASA - Error: {args.ErrorMessage}");
_spatialAnchorManager.AnchorLocated += OnAnchorLocated;
//_spatialAnchorManager.LocateAnchorsCompleted += OnLocateAnchorsCompleted;
await _spatialAnchorManager.StartSessionAsync();
return true;
}
/// <summary>
/// Stop the Azure Spatial Anchor Service session
/// </summary>
//public void StopSession()
//{
// if (this.cloudSpatialAnchorSession != null)
// {
// // stop session
// this.cloudSpatialAnchorSession.Stop();
// // clear event handlers
// this.cloudSpatialAnchorSession.Error -= this.OnCloudSessionError;
// this.cloudSpatialAnchorSession.AnchorLocated -= OnAnchorLocated;
// this.cloudSpatialAnchorSession.LocateAnchorsCompleted -= OnLocateAnchorsCompleted;
// // cleanup
// this.cloudSpatialAnchorSession.Dispose();
// this.cloudSpatialAnchorSession = null;
// }
//}
void OnLocateAnchorsCompleted(object sender, LocateAnchorsCompletedEventArgs args)
{
Debug.Log("On Locate Anchors Completed");
Debug.Assert(this.taskWaitForAnchorLocation != null);
if (!this.taskWaitForAnchorLocation.Task.IsCompleted)
{
this.taskWaitForAnchorLocation.TrySetResult(null);
}
}
void OnAnchorLocated(object sender, AnchorLocatedEventArgs args)
{
Debug.Log($"On Anchor Located, status is {args.Status} anchor is {args.Anchor?.Identifier}, pointer is {args.Anchor?.LocalAnchor}");
Debug.Assert(this.taskWaitForAnchorLocation != null);
this.taskWaitForAnchorLocation.SetResult(args.Anchor);
}
void OnCloudSessionError(object sender, SessionErrorEventArgs args)
{
Debug.Log($"On Cloud Session Error: {args.ErrorMessage}");
}
void ThrowOnBadAuthConfiguration()
{
if (string.IsNullOrEmpty(this.Profile.AzureAccountId) ||
string.IsNullOrEmpty(this.Profile.AzureServiceKey))
{
throw new ArgumentNullException("Missing required configuration to connect to service");
}
}
}
}
PhotonScript.cs:
using System;
using System.Threading.Tasks;
using AzureSpatialAnchors;
using ExitGames.Client.Photon;
using Photon.Pun;
using Photon.Realtime;
public class PhotonScript : MonoBehaviourPunCallbacks
{
enum RoomStatus
{
None,
CreatedRoom,
JoinedRoom,
JoinedRoomDownloadedAnchor
}
public int emptyRoomTimeToLiveSeconds = 120;
RoomStatus roomStatus = RoomStatus.None;
void Start()
{
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
base.OnConnectedToMaster();
var roomOptions = new RoomOptions();
roomOptions.EmptyRoomTtl = this.emptyRoomTimeToLiveSeconds * 1000;
PhotonNetwork.JoinOrCreateRoom(ROOM_NAME, roomOptions, null);
}
public async override void OnJoinedRoom()
{
base.OnJoinedRoom();
// Note that the creator of the room also joins the room...
if (this.roomStatus == RoomStatus.None)
{
this.roomStatus = RoomStatus.JoinedRoom;
}
await this.PopulateAnchorAsync();
}
public async override void OnCreatedRoom()
{
base.OnCreatedRoom();
this.roomStatus = RoomStatus.CreatedRoom;
await this.CreateAnchorAsync();
}
async Task CreateAnchorAsync()
{
// If we created the room then we will attempt to create an anchor for the parent
// of the cubes that we are creating.
var anchorService = this.GetComponent<AzureSpatialAnchorService>();
var anchorId = await anchorService.CreateAnchorOnObjectAsync(this.gameObject);
// Put this ID into a custom property so that other devices joining the
// room can get hold of it.
#if UNITY_2020
PhotonNetwork.CurrentRoom.SetCustomProperties(
new Hashtable()
{
{ ANCHOR_ID_CUSTOM_PROPERTY, anchorId }
}
);
#endif
}
async Task PopulateAnchorAsync()
{
if (this.roomStatus == RoomStatus.JoinedRoom)
{
object keyValue = null;
#if UNITY_2020
// First time around, this property may not be here so we see if is there.
if (PhotonNetwork.CurrentRoom.CustomProperties.TryGetValue(
ANCHOR_ID_CUSTOM_PROPERTY, out keyValue))
{
// If the anchorId property is present then we will try and get the
// anchor but only once so change the status.
this.roomStatus = RoomStatus.JoinedRoomDownloadedAnchor;
// If we didn't create the room then we want to try and get the anchor
// from the cloud and apply it.
var anchorService = this.GetComponent<AzureSpatialAnchorService>();
await anchorService.PopulateAnchorOnObjectAsync(
(string)keyValue, this.gameObject);
}
#endif
}
}
public async override void OnRoomPropertiesUpdate(Hashtable propertiesThatChanged)
{
base.OnRoomPropertiesUpdate(propertiesThatChanged);
await this.PopulateAnchorAsync();
}
static readonly string ANCHOR_ID_CUSTOM_PROPERTY = "anchorId";
static readonly string ROOM_NAME = "HardCodedRoomName";
}
From reviewing the code and scenario, I am reading that this is in same local area. So, the ASA service will have the shared anchor as detailed in docs:
https://learn.microsoft.com/en-us/windows/mixed-reality/design/shared-experiences-in-mixed-reality
"Shared static holograms (no interactions)
Leverage Azure Spatial Anchors in your app. Enabling and sharing spatial anchors across devices allows you to create an application where users see holograms in the same place at the same time. Additional syncing across devices is needed to enable users to interact with holograms and see movements or state updates of holograms."
The tutorial that Microsoft docs point to is here if it helps comparison to the other sample:
https://learn.microsoft.com/en-us/windows/mixed-reality/develop/unity/tutorials/mr-learning-sharing-01
Is there an event equivalent to WinForm's Load, that is called when the GUI window is actually created (not the constructor)? I am using GTK# and this library has no documentation and it is quite different from plain GTK, so it is hard for me to get information from the plain GTK documentation. I tried to guess the event by trying the following code but none of them worked.
protected override void OnRealized()
{
base.OnRealized();
Debug.WriteLine("realsed");
}
protected override void OnActivate()
{
base.OnActivate();
Debug.WriteLine("act");
}
protected override void OnShown()
{
base.OnShown();
Debug.WriteLine("shown");
}
protected override void OnStateChanged(StateType previous_state)
{
base.OnStateChanged(previous_state);
Debug.WriteLine("state");
}
protected override bool OnDrawn(Context cr)
{
return base.OnDrawn(cr);
Debug.WriteLine("drawn");
}
protected override bool OnWindowStateEvent(EventWindowState evnt)
{
Debug.WriteLine("win state");
return base.OnWindowStateEvent(evnt);
}
protected override void OnScreenChanged(Screen previous_screen)
{
base.OnScreenChanged(previous_screen);
Debug.WriteLine("screen");
}
Hey guys I'm learning how to create a character controller via the state pattern, which is pretty snazzy, but I'm running into this weird error
I've got a state machine pattern put together so this should be pretty straightforward and easy to handle, but it's kinda confusing. I tried freezing him in the state to see if he was transitioning from wallgrab to wallslide, but when I stop the velocity on the x and y he still slides. There's no other movement physics being applied at this time (why I'd recommend the state pattern), but for some reason his movement isn't being frozen. I can't pin a reason as to why, other than point you to my code and my github, and hope someone like my pixel art and has fun with the movement for a little bit.
All the code is in the scripts folder within the assets folder, and the states are within Assets > Scripts > Player > and then there are two folders (sub and super) The WallGrabState inherits from the PlayerTouchingWallState, and the logic is coming mainly from the WallGrabState for the physics. I'm just setting the x and y to zero, and yet he still slides, and idk what to do.
PlayerTouchingWall inherits the main state logic from playerState, and the player script loads all the states together and holds the physics and miscellaneous functions. The link to my github project is here https://github.com/roninMo/2d-Intro-Unity-Project
Here's the PlayerWallSlideState:
using UnityEngine;
public class PlayerWallSlideState : PlayerTouchingWallState
{
public PlayerWallSlideState(Player player, PlayerStateMachine stateMachine, PlayerData playerData, string currentAnimation) : base(player, stateMachine, playerData, currentAnimation)
{
}
public override void LogicUpdate()
{
base.LogicUpdate();
player.SetVelocityY(-playerData.wallslideVelocity);
// State logic
if (grabInput && input.y > 0)
{
player.StateMachine.ChangeState(player.wallGrabState);
}
}
}
And Here's the PlayerTouchingWallState:
using UnityEngine;
public class PlayerTouchingWallState : PlayerState
{
protected bool isTouchingGround;
protected bool isTouchingWall;
protected Vector2 input;
protected bool grabInput;
public PlayerTouchingWallState(Player player, PlayerStateMachine stateMachine, PlayerData playerData, string currentAnimation) : base(player, stateMachine, playerData, currentAnimation)
{
}
public override void Enter()
{
base.Enter();
}
public override void Exit()
{
base.Exit();
}
public override void LogicUpdate()
{
base.LogicUpdate();
input = player.InputHandler.RawMovementInput;
grabInput = player.InputHandler.GrabInput;
// State logic
if (isTouchingGround && !grabInput)
{
StateMachine.ChangeState(player.IdleState);
}
else if (!isTouchingWall || (input.x != player.FacingDirection && !grabInput))
{
StateMachine.ChangeState(player.InAirState);
}
}
public override void PhysicsUpdate()
{
base.PhysicsUpdate();
}
public override void DoChecks()
{
base.DoChecks();
isTouchingGround = player.CheckIfTouchingGround();
isTouchingWall = player.CheckIfTouchingWall();
}
}
The problem is that unity still applys physics to the character. I stopped it by grabbing the transform, and setting the player the position it entered in this state, along with freezing the velocity. Setting the transform is enough, but the camera was dragging upwards in place... So freezing the velocity fixed that. Anyways here's the code:
using UnityEngine;
public class PlayerWallGrabState : PlayerTouchingWallState
{
private Vector2 holdPosition;
public PlayerWallGrabState(Player player, PlayerStateMachine stateMachine, PlayerData playerData, string currentAnimation) : base(player, stateMachine, playerData, currentAnimation)
{
}
public override void Enter()
{
base.Enter();
holdPosition = player.transform.position;
HoldPosition();
}
public override void Exit()
{
base.Exit();
}
public override void LogicUpdate()
{
base.LogicUpdate();
HoldPosition();
// State logic
if (input.y > 0)
{
StateMachine.ChangeState(player.wallClimbState);
}
else if (input.y < 0 || !grabInput)
{
StateMachine.ChangeState(player.wallSlideState);
}
}
public override void PhysicsUpdate()
{
base.PhysicsUpdate();
}
public override void DoChecks()
{
base.DoChecks();
}
private void HoldPosition()
{
player.transform.position = holdPosition;
player.SetVelocityX(0f);
player.SetVelocityY(0f);
}
}
I have multiple game objects as children of ImageTarget.
Ar camera
world center mode= first_target
Track device pose checked and positional
As i initiate the game mode.
All the objects start to fall(sphere collider and mesh renderer turns off).
As i scan the target the object have already fallen through the plane i had under them(the plane has a mesh collider on it).
If I the scan the target as soon as I initiate Game mode all goes according to plan, the spheres collide with the plane and stay on top of it.
Is it possible to freeze the Y axis of the objects until the target is scanned and how do i enable extended tracking (Objects pass through the plane as soon as i move the camera away from the target and re-scan the target).
Vuforia has the DefaultTrackableEventHandler .. the code was hard to find (source) but it looks like this
/*==============================================================================
Copyright (c) 2017 PTC Inc. All Rights Reserved.
Copyright (c) 2010-2014 Qualcomm Connected Experiences, Inc.
All Rights Reserved.
Confidential and Proprietary - Protected under copyright and other laws.
==============================================================================*/
/*
* Modified by PauloSalvatore on 04/03/2018 - 15:38 (GMT-3)
*
* Change Log:
*
* Track Events added on Inspector
* Custom events can be added to be invoked during initialization,
* when appear start, when object is appearing and when disappear start.
*/
using UnityEngine;
using UnityEngine.Events;
using Vuforia;
[System.Serializable]
public class TrackEvents
{
#region PUBLIC_EVENTS
public UnityEvent onInitialized;
public UnityEvent onAppear;
public UnityEvent isAppearing;
public UnityEvent onDisappear;
#endregion PUBLIC_EVENTS
}
/// <summary>
/// A custom handler that implements the ITrackableEventHandler interface.
/// </summary>
public class DefaultTrackableEventHandler : MonoBehaviour, ITrackableEventHandler
{
#region PUBLIC_EVENTS
public TrackEvents trackEvents;
#endregion PUBLIC_EVENTS
#region PRIVATE_MEMBER_VARIABLES
protected TrackableBehaviour mTrackableBehaviour;
#endregion PRIVATE_MEMBER_VARIABLES
#region UNTIY_MONOBEHAVIOUR_METHODS
protected virtual void Start()
{
mTrackableBehaviour = GetComponent<TrackableBehaviour>();
if (mTrackableBehaviour)
mTrackableBehaviour.RegisterTrackableEventHandler(this);
// onInitialized custom events
if (trackEvents.onInitialized != null)
trackEvents.onInitialized.Invoke();
}
protected virtual void Update()
{
// isAppearing custom events
if (trackEvents.isAppearing != null)
trackEvents.isAppearing.Invoke();
}
#endregion UNTIY_MONOBEHAVIOUR_METHODS
#region PUBLIC_METHODS
/// <summary>
/// Implementation of the ITrackableEventHandler function called when the
/// tracking state changes.
/// </summary>
public void OnTrackableStateChanged(
TrackableBehaviour.Status previousStatus,
TrackableBehaviour.Status newStatus)
{
if (newStatus == TrackableBehaviour.Status.DETECTED ||
newStatus == TrackableBehaviour.Status.TRACKED ||
newStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
{
Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " found");
OnTrackingFound();
}
else if (previousStatus == TrackableBehaviour.Status.TRACKED &&
newStatus == TrackableBehaviour.Status.NOT_FOUND)
{
Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " lost");
OnTrackingLost();
}
else
{
// For combo of previousStatus=UNKNOWN + newStatus=UNKNOWN|NOT_FOUND
// Vuforia is starting, but tracking has not been lost or found yet
// Call OnTrackingLost() to hide the augmentations
OnTrackingLost();
}
}
#endregion PUBLIC_METHODS
#region PRIVATE_METHODS
protected virtual void OnTrackingFound()
{
var rendererComponents = GetComponentsInChildren<Renderer>(true);
var colliderComponents = GetComponentsInChildren<Collider>(true);
var canvasComponents = GetComponentsInChildren<Canvas>(true);
// Enable rendering:
foreach (var component in rendererComponents)
component.enabled = true;
// Enable colliders:
foreach (var component in colliderComponents)
component.enabled = true;
// Enable canvas:
foreach (var component in canvasComponents)
component.enabled = true;
// onAppear custom events
if (trackEvents.onAppear != null)
trackEvents.onAppear.Invoke();
}
protected virtual void OnTrackingLost()
{
var rendererComponents = GetComponentsInChildren<Renderer>(true);
var colliderComponents = GetComponentsInChildren<Collider>(true);
var canvasComponents = GetComponentsInChildren<Canvas>(true);
// Disable rendering:
foreach (var component in rendererComponents)
component.enabled = false;
// Disable colliders:
foreach (var component in colliderComponents)
component.enabled = false;
// Disable canvas:
foreach (var component in canvasComponents)
component.enabled = false;
// onDisappear custom events
if (trackEvents.onDisappear != null)
trackEvents.onDisappear.Invoke();
}
#endregion PRIVATE_METHODS
}
This should be placed on the according ImageTarget or whatever target you are using by defualt afaik. As you can see they are disabling the Renderer, Collider etc if the target is lost ... I personally would always remove this and instead replace it by UnityEvent so I can decide later what should be happening and what not.
Since the two methods OnTrackingFound() and OnTrackingLost() are virtual you can inherit from DefaultTrackableEventHandler and override/replace their functionality. By not also calling base.OnTrackingFound() or base.OnTrackingLost() we are telling c# to not execute whatever the parent class originally implemented but to only use what we implement:
// This is used to directly pass a string value into the event
// I'll explain why later ...
[Serializable]
public class VuforiaTargetFoundEvent : UnityEvent<string, Transform> { }
public MyTrackableEventHandler : DefaultTrackableEventHandler
{
// Give this specific VuforiaTarget a certain custom ID
// We will pass it dynamically into the UnityEvent
// so every listener automatically also knows WHICH target
// was lost or found
public string TargetID;
public VuforiaTargetEvent _OnTrackingFound;
public VuforiaTargetEvent _OnTrackingLost;
protected override void OnTrackingFound()
{
// call _OnTrackingFound with your specific target ID and
// also pass in the Transform so every listener can know
// WHICH target was found and WHERE it is positioned
_OnTrackingFound?
}
protected override void OnTrackingLost()
{
// call _OnTrackingLost with your specific target ID and
// also pass in the Transform so every listener can know
// WHICH target was lost and WHERE it was last positioned
_OnTrackingLost?
}
}
Simply place this on the Vuforia target instead of the DefaultTrackableEventHandler (if it was even there already) so now by default none of the Renderer,Collider etc in children will be disabled. (If you still need it you can ofcourse again add the base.OnTrackingLost() and base.OnTrackingFound() or alternatively implement it in a separate script and reference the according methods as callbacks in our just newly added UnityEvents ;) )
Now to your falling objects. At the beginning set useGravity to false so they don't fall down anymore. Then as a callback once the imagetarget was found enable it.
public GravityEnabler : MonoBehaviour
{
// either reference this in the Inspector ...
public RigidBody _rigidBody;
// also this either reference it in the Inspector ...
public MyTrackableEventHandler target;
// ... or get them on runtime
private void Awake()
{
if(!_rigidBody) _rigidBody = GetComponent<RigidBody>();
if(!target= target = FindObjectOfType<MyTrackableEventHandler>();
// before start disable gravity
_rigidBody.useGravity = false;
// setup the callback for the target
target._OnTrackingFound.AddListener(OnTargetScanned);
target._OnTrackingLost.AddListener(OnTargetLost);
}
privtae void OnDestroy()
{
// If this object gets destroyed be sure to remove the callbacks
// otherwise you would get exceptions because the callbacks
// would still exist but point to a NULL reference
target._OnTrackingFound.RemoveListener(OnTargetScanned);
target._OnTrackingLost.RemoveListener(OnTargetLost);
}
public void OnTargetFound(string targetID, Transform targetTransform)
{
_rigidBody.useGravity = true;
}
public void OnTargetLost(string targetID, Transform targetTransform)
{
// If you need to do anything here
// maybe you want to stop the falling again when the target is lost
_rigidBody.useGravity = false;
_rigidBody.velocity = Vector3.zero;
}
}
Place this on every of your faling objects and maybe setup the references already in the Inspector if possible (a bit more efficient).
Within a XAML user control, the Frame object is null:
this.Frame.Navigate(typeof(FaxPropertiesPage));
How do I navigate between pages with a Windows 8 XAML User Control? I have placed the control within a Callisto Flyout on a XAML page.
The search button below must navigate the user to another XAML page.
I've successfully used the code from app.xaml.cs
Frame frame = Window.Current.Content as Frame;
and then used the standard Navigate code.
There's the nice way and the not-so-nice way:
Both of them start with a navigation service:
public interface INavigationService
{
bool CanGoBack { get; }
void GoBack();
void GoForward();
bool Navigate<T>(object parameter = null);
bool Navigate(Type source, object parameter = null);
void ClearHistory();
event EventHandler<NavigatingCancelEventArgs> Navigating;
}
public class NavigationService : INavigationService
{
private readonly Frame _frame;
public NavigationService(Frame frame)
{
_frame = frame;
frame.Navigating += FrameNavigating;
}
#region INavigationService Members
public void GoBack()
{
_frame.GoBack();
}
public void GoForward()
{
_frame.GoForward();
}
public bool Navigate<T>(object parameter = null)
{
Type type = typeof (T);
return Navigate(type, parameter);
}
So, where do I get the Frame? In App.xaml.cs
protected async override void OnLaunched(LaunchActivatedEventArgs args)
{
// Do not repeat app initialization when already running, just ensure that
// the window is active
if (args.PreviousExecutionState == ApplicationExecutionState.Running)
{
Window.Current.Activate();
return;
}
// Create a Frame to act as the navigation context and navigate to the first page
var rootFrame = new Frame();
if (DesignMode.DesignModeEnabled)
SimpleIoc.Default.Register<INavigationService, DesignTimeNavigationService>();
else
SimpleIoc.Default.Register<INavigationService>(() => new NavigationService(rootFrame));
I'm using MVVM Light here. This makes life easy because all my viewmodels get created using dependency injection and have their services injected into them.
If you're not using something like MVVM Light and rely on code-behind then you can still make this work: Just make the navigation service static
public class NavigationService : INavigationService
{
public static INavigationService Current{
get;set;}
blah blah blah
}
And change App.xaml.cs to:
protected async override void OnLaunched(LaunchActivatedEventArgs args)
{
// Do not repeat app initialization when already running, just ensure that
// the window is active
if (args.PreviousExecutionState == ApplicationExecutionState.Running)
{
Window.Current.Activate();
return;
}
// Create a Frame to act as the navigation context and navigate to the first page
var rootFrame = new Frame();
NavigationService.Current= new NavigationService(rootFrame));
}
And you can then access your main Frame anywhere in the app by saying:
NavigationService.Current.Navigate<MyView>();
simple code ( may not be 100% efficient) is :
Frame frame = new Frame();
frame.Navigate(typeof(ExerciseAddPage)