I have an object which if it gets to a certain state, I create a new object:
if (currentShape.State == ShapeState.Landed)
{
Shape shape = new Shape();
shape = utilities.GetRandomShape(contentManager);
shapes.Add(shape);
currentShape = shape;
}
The object currentShape keeps changing in this manner. For some reason however, currentShape is still ShapeState.Landed forever.
The game which I have has objects falling, when one reaches the ground, another one is created and it is assigned to currentShape. So whenever currentShape lands, another one is created... as mentioned.
The logic for the Update method is as follows:
public void Update(TimeSpan elapsedTime, List<Shape> shapes, Shape fallingShape)
{
List<Shape> shapesInSameColumn = new List<Shape>();
foreach (var shape in shapes)
{
if (shape.ColumnNumber == fallingShape.ColumnNumber)
{
shapesInSameColumn.Add(shape);
}
}
shapesInSameColumn.Remove(fallingShape);
float yDestination = 0f;
float yNextPosition = fallingShape.Position.Y + elapsedTime.Milliseconds / 30 * FallSpeed;
if (shapesInSameColumn.Count == 0) // There are NO shapes in the column
{
yDestination = Utilities.bottomOfCanvas;
if (yNextPosition > yDestination)
{
fallingShape.Position.Y = yDestination;
fallingShape.State = ShapeState.Landed;
return;
}
else
{
fallingShape.Position.Y = yNextPosition;
}
}
else // There ARE shapes in the column
{
yDestination = shapesInSameColumn[shapesInSameColumn.Count - 1].Position.Y - Texture.Height;
if (yNextPosition > yDestination)
{
fallingShape.Position.Y = yDestination;
fallingShape.State = ShapeState.Landed;
return;
}
else
{
fallingShape.Position.Y = yNextPosition;
}
}
}
UPDATE
After a few frames, it goes in to an endless loop of adding Shapes to the collection as the State is always Landed.
This is what it sounds like you have (correct me if I'm mistaken):
public void Update(TimeSpan elapsedTime, List<Shape> shapes, Shape fallingShape)
{
List<Shape> shapesInSameColumn = new List<Shape>();
//Added code.
if (currentShape.State == ShapeState.Landed)
{
Shape shape = new Shape();
shape = utilities.GetRandomShape(contentManager);
shapes.Add(shape);
currentShape = shape;
}
foreach (var shape in shapes)
{
if (shape.ColumnNumber == fallingShape.ColumnNumber)
{
shapesInSameColumn.Add(shape);
}
}
shapesInSameColumn.Remove(fallingShape);
float yDestination = 0f;
float yNextPosition = fallingShape.Position.Y + elapsedTime.Milliseconds / 30 * FallSpeed;
if (shapesInSameColumn.Count == 0) // There are NO shapes in the column
{
yDestination = Utilities.bottomOfCanvas;
if (yNextPosition > yDestination)
{
fallingShape.Position.Y = yDestination;
fallingShape.State = ShapeState.Landed;
return;
}
else
{
fallingShape.Position.Y = yNextPosition;
}
}
else // There ARE shapes in the column
{
yDestination = shapesInSameColumn[shapesInSameColumn.Count - 1].Position.Y - Texture.Height;
if (yNextPosition > yDestination)
{
fallingShape.Position.Y = yDestination;
fallingShape.State = ShapeState.Landed;
return;
}
else
{
fallingShape.Position.Y = yNextPosition;
}
}
}
So that means that it will still continue to update after the //Added code executes, correct? The fix is to not update if currentShape.State == ShapeState.Landed.
Related
I have button's horizontal layout group with TextMeshPro. How can I calculate auto sizing font for it and set minimum value on all buttons? It's need for relative UI.
I have now:
And how I want:
I tried this code:
public class FontSizeController: MonoBehaviour
{
private void Start()
{
SetMinFontForAnswers(transform,
FindMinFontSizeAnswerOptions(transform));
}
private void SetMinFontForAnswers(Transform answerPanel, float minFontSize)
{
for (var answerIndex = 0; answerIndex < answerPanel.childCount; answerIndex++)
{
var meshProUgui = answerPanel.GetChild(answerIndex).GetChild(1).GetComponent<TextMeshProUGUI>();
meshProUgui.fontSize = minFontSize;
}
}
private float FindMinFontSizeAnswerOptions(Transform answerOptions)
{
var minFontSize = -1f;
for (var answerIndex = 0; answerIndex < answerOptions.childCount; answerIndex++)
{
var component = answerOptions.GetChild(answerIndex).GetChild(1).GetComponent<TextMeshProUGUI>();
component.enableAutoSizing = true;
component.ForceMeshUpdate();
if (IsAnswerOptionActive(answerOptions, answerIndex) && IsMinFontSizeOrNotInitialized(component, minFontSize))
{
minFontSize = component.fontSize;
}
component.enableAutoSizing = false;
}
return minFontSize;
}
private bool IsAnswerOptionActive(Transform answerOptions, int answerIndex)
{
return answerOptions.GetChild(answerIndex).gameObject.activeSelf;
}
private bool IsMinFontSizeOrNotInitialized(TMP_Text textComponent, float minFontSize)
{
return textComponent.fontSize < minFontSize || minFontSize == -1f;
}
}
But it doesn't work on Start and work only in Update method. But when I used it in Update method I can see when text font size changing. It is quickly but I want do this before panel will be render.
Question panel is not active by default
AnswerOptionsPanel:
TextMeshPro Text in AnswerOptionsPanel:
You can get your Text assets current size with using this method;
Text.cachedTextGenerator.fontSizeUsedForBestFit
You can compare your texts instant size and then change.
For example;
UnityEngine.UI.Text[] myTexts;
void OptimiseTextSizes()
{
int minSize = 999;
foreach (UnityEngine.UI.Text t in myTexts)
{
if (t.cachedTextGenerator.fontSizeUsedForBestFit < minSize)
{
minSize = t.cachedTextGenerator.fontSizeUsedForBestFit;
}
}
foreach (UnityEngine.UI.Text t in myTexts)
{
t.resizeTextMaxSize = minSize;
}
}
I need to get value from another script but I keep getting this error that says
The type name 'head' does not exist in the type 'SteamVR_Camera'.
My code:
using UnityEngine;
using System.Collections;
using UnityEngine.VR;
public class HMDHelper : MonoBehaviour
{
private SteamVR_Camera.head.localPosition HMDLocalPos; //Error is thrown here.
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("g"))
{
AutoRotate();
}
}
void AutoRotate()
{
HMDLocalPos = InputTracking.GetLocalPosition(Head);
Debug.Log(HMDLocalPos);
}
}
What exactly do I have to do to fix error?
This is the script that I retrieved the other value (HMDLocalPos) from...
//========= Copyright 2014, Valve Corporation, All rights reserved. ===========
//
// Purpose: Adds SteamVR render support to existing camera objects
//
//=============================================================================
using UnityEngine;
using System.Collections;
using System.Reflection;
using Valve.VR;
[RequireComponent(typeof(Camera))]
public class SteamVR_Camera : MonoBehaviour
{
[SerializeField]
private Transform _head;
public Transform head { get { return _head; } }
public Transform offset { get { return _head; } } // legacy
public Transform origin { get { return _head.parent; } }
[SerializeField]
private Transform _ears;
public Transform ears { get { return _ears; } }
public Ray GetRay()
{
return new Ray(_head.position, _head.forward);
}
public bool wireframe = false;
[SerializeField]
private SteamVR_CameraFlip flip;
#region Materials
static public Material blitMaterial;
// Using a single shared offscreen buffer to render the scene. This needs to be larger
// than the backbuffer to account for distortion correction. The default resolution
// gives us 1:1 sized pixels in the center of view, but quality can be adjusted up or
// down using the following scale value to balance performance.
static public float sceneResolutionScale = 1.0f;
static private RenderTexture _sceneTexture;
static public RenderTexture GetSceneTexture(bool hdr)
{
var vr = SteamVR.instance;
if (vr == null)
return null;
int w = (int)(vr.sceneWidth * sceneResolutionScale);
int h = (int)(vr.sceneHeight * sceneResolutionScale);
int aa = QualitySettings.antiAliasing == 0 ? 1 : QualitySettings.antiAliasing;
var format = hdr ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
if (_sceneTexture != null)
{
if (_sceneTexture.width != w || _sceneTexture.height != h || _sceneTexture.antiAliasing != aa || _sceneTexture.format != format)
{
Debug.Log(string.Format("Recreating scene texture.. Old: {0}x{1} MSAA={2} [{3}] New: {4}x{5} MSAA={6} [{7}]",
_sceneTexture.width, _sceneTexture.height, _sceneTexture.antiAliasing, _sceneTexture.format, w, h, aa, format));
Object.Destroy(_sceneTexture);
_sceneTexture = null;
}
}
if (_sceneTexture == null)
{
_sceneTexture = new RenderTexture(w, h, 0, format);
_sceneTexture.antiAliasing = aa;
#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
// OpenVR assumes floating point render targets are linear unless otherwise specified.
var colorSpace = (hdr && QualitySettings.activeColorSpace == ColorSpace.Gamma) ? EColorSpace.Gamma : EColorSpace.Auto;
SteamVR.Unity.SetColorSpace(colorSpace);
#endif
}
return _sceneTexture;
}
#endregion
#region Enable / Disable
void OnDisable()
{
SteamVR_Render.Remove(this);
}
void OnEnable()
{
#if !(UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
// Convert camera rig for native OpenVR integration.
var t = transform;
if (head != t)
{
Expand();
t.parent = origin;
while (head.childCount > 0)
head.GetChild(0).parent = t;
DestroyImmediate(head.gameObject);
_head = t;
}
if (flip != null)
{
DestroyImmediate(flip);
flip = null;
}
if (!SteamVR.usingNativeSupport)
{
enabled = false;
return;
}
#else
// Bail if no hmd is connected
var vr = SteamVR.instance;
if (vr == null)
{
if (head != null)
{
head.GetComponent<SteamVR_GameView>().enabled = false;
head.GetComponent<SteamVR_TrackedObject>().enabled = false;
}
if (flip != null)
flip.enabled = false;
enabled = false;
return;
}
// Ensure rig is properly set up
Expand();
if (blitMaterial == null)
{
blitMaterial = new Material(Shader.Find("Custom/SteamVR_Blit"));
}
// Set remaining hmd specific settings
var camera = GetComponent<Camera>();
camera.fieldOfView = vr.fieldOfView;
camera.aspect = vr.aspect;
camera.eventMask = 0; // disable mouse events
camera.orthographic = false; // force perspective
camera.enabled = false; // manually rendered by SteamVR_Render
if (camera.actualRenderingPath != RenderingPath.Forward && QualitySettings.antiAliasing > 1)
{
Debug.LogWarning("MSAA only supported in Forward rendering path. (disabling MSAA)");
QualitySettings.antiAliasing = 0;
}
// Ensure game view camera hdr setting matches
var headCam = head.GetComponent<Camera>();
if (headCam != null)
{
headCam.hdr = camera.hdr;
headCam.renderingPath = camera.renderingPath;
}
#endif
ears.GetComponent<SteamVR_Ears>().vrcam = this;
SteamVR_Render.Add(this);
}
#endregion
#region Functionality to ensure SteamVR_Camera component is always the last component on an object
void Awake() { ForceLast(); }
static Hashtable values;
public void ForceLast()
{
if (values != null)
{
// Restore values on new instance
foreach (DictionaryEntry entry in values)
{
var f = entry.Key as FieldInfo;
f.SetValue(this, entry.Value);
}
values = null;
}
else
{
// Make sure it's the last component
var components = GetComponents<Component>();
// But first make sure there aren't any other SteamVR_Cameras on this object.
for (int i = 0; i < components.Length; i++)
{
var c = components[i] as SteamVR_Camera;
if (c != null && c != this)
{
if (c.flip != null)
DestroyImmediate(c.flip);
DestroyImmediate(c);
}
}
components = GetComponents<Component>();
#if !(UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
if (this != components[components.Length - 1])
{
#else
if (this != components[components.Length - 1] || flip == null)
{
if (flip == null)
flip = gameObject.AddComponent<SteamVR_CameraFlip>();
#endif
// Store off values to be restored on new instance
values = new Hashtable();
var fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var f in fields)
if (f.IsPublic || f.IsDefined(typeof(SerializeField), true))
values[f] = f.GetValue(this);
var go = gameObject;
DestroyImmediate(this);
go.AddComponent<SteamVR_Camera>().ForceLast();
}
}
}
#endregion
#region Expand / Collapse object hierarchy
#if UNITY_EDITOR
public bool isExpanded { get { return head != null && transform.parent == head; } }
#endif
const string eyeSuffix = " (eye)";
const string earsSuffix = " (ears)";
const string headSuffix = " (head)";
const string originSuffix = " (origin)";
public string baseName { get { return name.EndsWith(eyeSuffix) ? name.Substring(0, name.Length - eyeSuffix.Length) : name; } }
// Object hierarchy creation to make it easy to parent other objects appropriately,
// otherwise this gets called on demand at runtime. Remaining initialization is
// performed at startup, once the hmd has been identified.
public void Expand()
{
var _origin = transform.parent;
if (_origin == null)
{
_origin = new GameObject(name + originSuffix).transform;
_origin.localPosition = transform.localPosition;
_origin.localRotation = transform.localRotation;
_origin.localScale = transform.localScale;
}
if (head == null)
{
_head = new GameObject(name + headSuffix, typeof(SteamVR_GameView), typeof(SteamVR_TrackedObject)).transform;
head.parent = _origin;
head.position = transform.position;
head.rotation = transform.rotation;
head.localScale = Vector3.one;
head.tag = tag;
var camera = head.GetComponent<Camera>();
camera.clearFlags = CameraClearFlags.Nothing;
camera.cullingMask = 0;
camera.eventMask = 0;
camera.orthographic = true;
camera.orthographicSize = 1;
camera.nearClipPlane = 0;
camera.farClipPlane = 1;
camera.useOcclusionCulling = false;
}
if (transform.parent != head)
{
transform.parent = head;
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
transform.localScale = Vector3.one;
while (transform.childCount > 0)
transform.GetChild(0).parent = head;
var guiLayer = GetComponent<GUILayer>();
if (guiLayer != null)
{
DestroyImmediate(guiLayer);
head.gameObject.AddComponent<GUILayer>();
}
var audioListener = GetComponent<AudioListener>();
if (audioListener != null)
{
DestroyImmediate(audioListener);
_ears = new GameObject(name + earsSuffix, typeof(SteamVR_Ears)).transform;
ears.parent = _head;
ears.localPosition = Vector3.zero;
ears.localRotation = Quaternion.identity;
ears.localScale = Vector3.one;
}
}
if (!name.EndsWith(eyeSuffix))
name += eyeSuffix;
}
public void Collapse()
{
transform.parent = null;
// Move children and components from head back to camera.
while (head.childCount > 0)
head.GetChild(0).parent = transform;
var guiLayer = head.GetComponent<GUILayer>();
if (guiLayer != null)
{
DestroyImmediate(guiLayer);
gameObject.AddComponent<GUILayer>();
}
if (ears != null)
{
while (ears.childCount > 0)
ears.GetChild(0).parent = transform;
DestroyImmediate(ears.gameObject);
_ears = null;
gameObject.AddComponent(typeof(AudioListener));
}
if (origin != null)
{
// If we created the origin originally, destroy it now.
if (origin.name.EndsWith(originSuffix))
{
// Reparent any children so we don't accidentally delete them.
var _origin = origin;
while (_origin.childCount > 0)
_origin.GetChild(0).parent = _origin.parent;
DestroyImmediate(_origin.gameObject);
}
else
{
transform.parent = origin;
}
}
DestroyImmediate(head.gameObject);
_head = null;
if (name.EndsWith(eyeSuffix))
name = name.Substring(0, name.Length - eyeSuffix.Length);
}
#endregion
#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
#region Render callbacks
void OnPreRender()
{
if (flip)
flip.enabled = (SteamVR_Render.Top() == this && SteamVR.instance.graphicsAPI == EGraphicsAPIConvention.API_DirectX);
var headCam = head.GetComponent<Camera>();
if (headCam != null)
headCam.enabled = (SteamVR_Render.Top() == this);
if (wireframe)
GL.wireframe = true;
}
void OnPostRender()
{
if (wireframe)
GL.wireframe = false;
}
void OnRenderImage(RenderTexture src, RenderTexture dest)
{
if (SteamVR_Render.Top() == this)
{
int eventID;
if (SteamVR_Render.eye == EVREye.Eye_Left)
{
// Get gpu started on work early to avoid bubbles at the top of the frame.
SteamVR_Utils.QueueEventOnRenderThread(SteamVR.Unity.k_nRenderEventID_Flush);
eventID = SteamVR.Unity.k_nRenderEventID_SubmitL;
}
else
{
eventID = SteamVR.Unity.k_nRenderEventID_SubmitR;
}
// Queue up a call on the render thread to Submit our render target to the compositor.
SteamVR_Utils.QueueEventOnRenderThread(eventID);
}
Graphics.SetRenderTarget(dest);
SteamVR_Camera.blitMaterial.mainTexture = src;
GL.PushMatrix();
GL.LoadOrtho();
SteamVR_Camera.blitMaterial.SetPass(0);
GL.Begin(GL.QUADS);
GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(-1, 1, 0);
GL.TexCoord2(1.0f, 0.0f); GL.Vertex3( 1, 1, 0);
GL.TexCoord2(1.0f, 1.0f); GL.Vertex3( 1, -1, 0);
GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(-1, -1, 0);
GL.End();
GL.PopMatrix();
Graphics.SetRenderTarget(null);
}
#endregion
#endif
}
How do I fix this? Thank you.
The type is wrong. Needs to be Vector3.
private Vector3 HMDLocalPos;
void Start()
{
HDMLocalPos = SteamVR_Camera.head.localPosition;
}
Edit:
Replace the HDMLocalPos property with a reference to SteamVR_Camera and access it's properties like this:
public SteamVR_Camera steamCam; // popuplate this via inspector or with a Find() (or similar)
void Start()
{
// access like this
steamCam.head.localPosition = something
}
I think this is what you want (to actually change the head.localPosition of the camera).
I'm working on a tile game, but I ran into a big problem.
The idea is that if a tile is selected it turns red and a few tiles surounded turn blue. if you click one of the blue ones the unit of the slected one is transported to that one , but every time a do this my selected tile has a NullException . I can use the Tile itself, but non of the values or voids it contains which always return null. I'd be very thankfull if someone could pinpoint the problem
Code in order of likelyhood of problem
Part of Update():
while (j < baseLayer.MapDimensions.Y)
{
while (i < baseLayer.MapDimensions.X)
{
if (moveToMap[i, j] && standardCheck.Click(new Rectangle(i * 100, j * 100, 100, 100), mouseState, prevMouseState))
{
tileArray[i, j].changeColor = Color.Gold;
tileArray[i, j].MoveTo(tileArray[(int)selectedTile.X, (int)selectedTile.Y].Position,
tileArray[(int)selectedTile.X, (int)selectedTile.Y].getUnit);// problem occors here
//problem occurres here
}
else
{
tileArray[i, j].Checkclick(mouseState, prevMouseState, relativeMousePosition);
if (tileArray[i, j].ReturnIfSelected)
{
selectedTile = new Vector2(i, j);
}
else if (selectedTile == new Vector2(i, j))
selectedTile = new Vector2(200, 200);
}
i++;
}
i = 0;
j++;
}
j = 0;
Tile class
public Unit unit = new Unit();
public Unit Building = new Unit();
public Unit getUnit
{
get { return unit; }
}
public Color tileColor = Color.White;
public Vector2 position;
public Vector2 drawPosition;
public int[] map { set; get; } = new int[4];
public bool selected = false;
public void LoadContent(Vector2 _position ,int[,,] _map)
{
}
public void Checkclick(MouseState mS, MouseState prevMS,Vector2 matrixPosition)
{
}
}
public bool checkifselectable()
{
}
public void Update(int[,,] _map)
{
unit.Reset();
}
public void MoveTo(Vector2 oldTile,Unit _unit)
{
int change = 0;
if (oldTile.X - position.X != 0)
change = (int)(oldTile.X - position.X);
if (oldTile.Y - position.Y !=0)
change = (int)(oldTile.Y - position.Y);
unit = _unit;
map[2] = _unit.ID;
if (change>= 0)
unit.RemainingMoveSpeed = change;
if (change < 0)
unit.RemainingMoveSpeed = -change;
}
Thanks already for your time
The Young Programmer
Maybe you have NullReferenceException. In this case, this exception is thrown when there is an attempt to dereference a null object reference. This might help you https://msdn.microsoft.com/en-us/library/system.nullreferenceexception%28v=vs.110%29.aspx.
I'm working on a game app for windows phone.
I'm moving an image over the screen (which is a Map). The user can place a ball where he wants. My question is how can I not allow the ball to be placed on the image?
I think I could check for collision an move the ball out of the rectangle when if necessary.
I have 3 methods for moving my object (ManipulationStarted, OnManipulationDelta, and ManipulationOver).
The one I have a problem with is:
private void OnManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
Point A = new Point();
Point B = new Point();
e.Handled = true;
var transform = (sender as UIElement).RenderTransform as TranslateTransform;
A.X = transform.X += e.DeltaManipulation.Translation.X;
A.Y = transform.Y += e.DeltaManipulation.Translation.Y;
B.X = savx = transform.X;
B.Y = savy = transform.Y;
for (int i = 0; i < cur.lobst.Count(); i++)
{
if ((A.X > cur.lobst[i].px
&& A.X < (cur.lobst[i].px + cur.lobst[i].pw))
&& (A.Y > cur.lobst[i].py
&& A.Y < (cur.lobst[i].py + cur.lobst[i].ph)))
{
MessageBox.Show(
"Point inside the rectangle, so inside (under) my object ");
}
}
}
The message box is never shown. Why is that?
you can try this ...
public bool Intersects(Rect r1,Rect r2)
{
r1.Intersect(r2);
if(r1.IsEmpty)
{
return false;
}
else
{
return true;
}
}
then while checking ...
ismoveallowed = true;
for (int i = 0; i < cur.lobst.Count(); i++)
{
if(Intersects(r1,r2))
{
ismovallowed = false;
break;
}
}
if(ismovealoowed)
{
// move the object.
}
i hope this will help you ..
I have a problem with this code.
When I use MoveTo, my skeleton flicks through the screen. I have made some little changes to the original code (here):
lock skeleton position to a specific Z position
increase horizontal speed (X)
I use XNA 4.0 and I call that member into Draw "callback".
So, the question is: why does the skeleton flick?
private Skeleton MoveTo2(Skeleton skToBeMoved) {
Joint newJoint = new Joint();
///Based on the HipCenter
float howMuchMoveToX = ((skToBeMoved.Joints[JointType.HipCenter].Position.X - settings_skel_offset_x) * -1) * settings_skel_offset_x_mult;
float howMuchMoveToY = (skToBeMoved.Joints[JointType.HipCenter].Position.Y - settings_skel_offset_y) * -1;
float howMuchMoveToZ = (skToBeMoved.Joints[JointType.HipCenter].Position.Z - settings_skel_offset_z) * -1;
foreach (JointType item in Enum.GetValues(typeof(JointType)))
{
newJoint = skToBeMoved.Joints[item];
SkeletonPoint pos = new SkeletonPoint()
{
X = (float)(newJoint.Position.X + (howMuchMoveToX)),
Y = (float)(newJoint.Position.Y + (howMuchMoveToY)),
Z = (float)(newJoint.Position.Z + (howMuchMoveToZ)),
};
if (XnaBasics.settings_skel_lock_z)
{
pos.Z = settings_skel_offset_z;
}
newJoint.Position = pos;
Debug.WriteLine("SkelID: "+skToBeMoved.TrackingId+ " howMuchMoveToX: " + howMuchMoveToX + " oldPosX: " + skToBeMoved.Joints[item].Position.X + " newPosX: " + newJoint.Position.X);
skToBeMoved.Joints[item] = newJoint;
}
return skToBeMoved;
}
SOLVED
I put the member call into "Update" callback, before it was called from the "Draw" callback.
Correct Code (relevant part)
public override void Update(GameTime gameTime)
{
// Debug.WriteLine("= UPDATE - SkeletonStreamRender");
if (null == this.Chooser.Sensor || false == this.Chooser.Sensor.IsRunning || KinectStatus.Connected != this.Chooser.Sensor.Status)
{
return;
}
if (skeletonDrawn || !drawChk)
{
using (var skeletonFrame = this.Chooser.Sensor.SkeletonStream.OpenNextFrame(0))
{
if (null == skeletonData || skeletonData.Length != skeletonFrame.SkeletonArrayLength)
{
skeletonData = new Skeleton[skeletonFrame.SkeletonArrayLength];
}
skeletonFrame.CopySkeletonDataTo(skeletonData);
int counter = 0;
foreach (Skeleton s in skeletonData)
{
if (s.TrackingState == SkeletonTrackingState.Tracked)
{
playersID = s.TrackingId;
Skeleton skeleton = MoveTo2(s);
skeletonData[counter] = skeleton;
continue;
}
counter++;
}
skeletonDrawn = false;
}
[CUT]
Wrong call from Draw
public override void Draw(GameTime gameTime)
{
// Debug.WriteLine("== DRAW - SkeletonStreamRender");
// If the joint texture isn't loaded, load it now
if (null == this.jointTexture)
{
this.LoadContent();
}
// If we don't have data, lets leave
if (null == skeletonData || null == this.mapMethod)
{
return;
}
if (false == this.initialized)
{
this.Initialize();
}
this.SharedSpriteBatch.Begin();
foreach (var skeleton in skeletonData)
{
if (playersID != skeleton.TrackingId)
continue;
switch (skeleton.TrackingState)
{
case SkeletonTrackingState.NotTracked:
// non tracciato
break;
case SkeletonTrackingState.Tracked:
// blocco la posizione Z
Skeleton skeleton = MoveTo2(skeletonTmp);
// Draw Bones
this.DrawBone(skeleton.Joints, JointType.Head, JointType.ShoulderCenter);
this.DrawBone(skeleton.Joints, JointType.ShoulderCenter, JointType.ShoulderLeft);
this.DrawBone(skeleton.Joints, JointType.ShoulderCenter, JointType.ShoulderRight);
this.DrawBone(skeleton.Joints, JointType.ShoulderCenter, JointType.Spine);
[CUT]