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]
Related
Hello I'm trying to make a gun system and everything is working except Switching gun that stored in my GameObject array playerGuns, it always stores it on 0
and when I press another key it disabled every object that created.
I want to make it so when you will press 1-4 key on your keyboard it will switch
between the gun that stored on playerGuns and disables the other gun, you ware holding.
I couldn't find why the problem is happening so please help.
public GameObject Player;
public GameObject Showui;
public RectTransform Uirect;
public Material greenQu, blueQu;
public GameObject nameObject;
public GameObject rearityObject;
public GameObject dmgObject;
public GameObject levelObject;
private Text nameText;
private Text rearityText;
private Text dmgText;
private Text levelText;
private Image infoImage;
private Gunsystem gunScript;
private string gunName;
private int index = 0, index2 = 0;
private bool pressed = false, Show = false;
public Gun[] Inventory = new Gun[4];
public GameObject[] playerGuns = new GameObject[4] { null, null, null, null};
public int keyPress = 0;
void Start () {
gunScript = Player.GetComponent<Gunsystem>();
infoImage = Showui.GetComponent<Image>();
//Get text from objects
nameText = nameObject.GetComponent<Text>();
rearityText = rearityObject.GetComponent<Text>();
dmgText = dmgObject.GetComponent<Text>();
levelText = levelObject.GetComponent<Text>();
gunName = gameObject.name;
Debug.Log(gunName);
}
private void Update()
{
KeyCode pickup = KeyCode.E;
KeyCode key1 = KeyCode.Alpha1;
KeyCode key2 = KeyCode.Alpha2;
KeyCode key3 = KeyCode.Alpha3;
KeyCode key4 = KeyCode.Alpha4;
//Handling inventory keys
if (Input.GetKeyDown(key1))
{
keyPress = 0;
if (playerGuns[0] != null && !playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(true);
}
if (playerGuns[1] != null && playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(false);
}else if (playerGuns[2] != null && playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(false);
}
else if (playerGuns[3] != null && playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(false);
}
}else if (Input.GetKeyDown(key2))
{
keyPress = 1;
if (playerGuns[1] != null && !playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(true);
}
if (playerGuns[0] != null && playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(false);
}
else if (playerGuns[2] != null && playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(false);
}
else if (playerGuns[3] != null && playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(false);
}
}else if (Input.GetKeyDown(key3))
{
keyPress = 2;
if (playerGuns[2] != null && !playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(true);
}
if (playerGuns[0] != null && playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(false);
}
else if (playerGuns[1] != null && playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(false);
}
else if (playerGuns[3] != null && playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(false);
}
}
else if (Input.GetKeyDown(key4))
{
keyPress = 3;
if (playerGuns[3] != null && !playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(true);
}
if (playerGuns[0] != null && playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(false);
}
else if (playerGuns[1] != null && playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(false);
}
else if (playerGuns[2] != null && playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(false);
}
}
//Pick the gun when key pressed and store it
if (Input.GetKeyDown(pickup) && Show == true)
{
foreach (Gun item in gunScript.gunList)
{
if (index2 == Convert.ToInt32(gunName))
{
if (item.gunType == "Normal")
{
GameObject temp = GameObject.Find(gameObject.name);
playerGuns[keyPress] = Instantiate(temp, Player.transform.position, Quaternion.identity) as GameObject;
playerGuns[keyPress].name = gameObject.name;
playerGuns[keyPress].tag = gameObject.tag;
playerGuns[keyPress].transform.parent = Player.transform;
playerGuns[keyPress].transform.rotation.SetLookRotation(Player.transform.position);
//Change rigidbody and disable collider
playerGuns[keyPress].GetComponent<Rigidbody>().useGravity = false;
playerGuns[keyPress].GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;
playerGuns[keyPress].GetComponent<MeshCollider>().enabled = false;
//Store gundata in inventory
item.Named = false;
Inventory[keyPress] = item;
pressed = true;
}
else if (item.gunType == "Stride")
{
GameObject temp = GameObject.Find(gameObject.name);
playerGuns[keyPress] = Instantiate(temp, Player.transform.position, Quaternion.identity) as GameObject;
playerGuns[keyPress].name = gameObject.name;
playerGuns[keyPress].tag = gameObject.tag;
playerGuns[keyPress].transform.parent = Player.transform;
playerGuns[keyPress].transform.rotation.SetLookRotation(Player.transform.position);
//Set rgidbody and disable collider
playerGuns[keyPress].GetComponent<Rigidbody>().useGravity = false;
playerGuns[keyPress].GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;
playerGuns[keyPress].GetComponent<MeshCollider>().enabled = false;
//Store gundata in inventory
item.Named = false;
Inventory[keyPress] = item;
pressed = true;
}
}
index2++;
}
index2 = 0;
}
}
private void OnMouseEnter()
{
Vector3 Pos = Camera.main.WorldToScreenPoint(transform.position);
Showui.transform.position = Pos;
Showui.transform.position += new Vector3(0, 90f, 0.5f);
gunScript.updateGuns = true;
Show = true;
foreach (Gun item in gunScript.gunList)
{
if (index == Convert.ToInt32(gunName))
{
if(item.gunType == "Normal")
{
infoImage.material = greenQu;
}else if (item.gunType == "Stride")
{
infoImage.material = blueQu;
}
LayoutRebuilder.ForceRebuildLayoutImmediate(Uirect);
if(item.Named != false)
Showui.SetActive(true);
nameText.text = "Name: " + item.Name;
rearityText.text = "Rearity: " + item.gunType;
dmgText.text = "Damage: " + Mathf.Round(item.Dmg).ToString();
levelText.text = "Level: " + item.gunLevel.ToString();
//Debug.Log(item.Name);
//Debug.Log(item.gunType);
//Debug.Log(item.Dmg);
//Debug.Log(item.gunLevel);
}
index++;
}
index = 0;
}
private void OnMouseExit()
{
Show = false;
Showui.SetActive(false);
}
I wrote a little script that should handle the activation and the deactivation of your four guns.
Hope It helps,
Alex
public GameObject[] Guns;
void Start(){
for (int i=0; i<3; i++){
if(Guns[i] == null) Debug.LogError("Gun n°" + i +" is null);
}
}
void Update(){
if(Input.GetKeyDown(Input.KeyCode.Alpha1)){
setGunActive(1);
}
if(Input.GetKeyDown(Input.KeyCode.Alpha2)){
setGunActive(2);
}
if(Input.GetKeyDown(Input.KeyCode.Alpha3)){
setGunActive(3);
}
if(Input.GetKeyDown(Input.KeyCode.Alpha4)){
setGunActive(4);
}
}
void setGunActive(int n){
foreach(GameObject g in Guns){
g.setActive(false);
}
Guns[n].setActive(true);
}
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 am currently attempting to show the x,y values whenever I mouse over a point on the chart but for the x axis is in a date/time format, and I want to display the date/time instead of the actual pixel value.
What I am currently using is this following code for the mouse over event
private void chart1_MouseMove(object sender, MouseEventArgs e)
{
var pos = e.Location;
if (prevPosition.HasValue && pos == prevPosition.Value)
return;
tooltip.RemoveAll();
prevPosition = pos;
var results = chart1.HitTest(pos.X, pos.Y, false,
ChartElementType.DataPoint);
foreach (var result in results)
{
if (result.ChartElementType == ChartElementType.DataPoint)
{
var prop = result.Object as DataPoint;
if (prop != null)
{
var pointXPixel = result.ChartArea.AxisX.ValueToPixelPosition(prop.XValue);
var pointYPixel = result.ChartArea.AxisY.ValueToPixelPosition(prop.YValues[0]);
// check if the cursor is really close to the point (2 pixels around the point)
if (Math.Abs(pos.X - pointXPixel) < 2 &&
Math.Abs(pos.Y - pointYPixel) < 2)
{
tooltip.Show("X=" + prop.XValue + ", Y=" + prop.YValues[0], this.chart1,
pos.X, pos.Y - 15);
}
}
}
}
}
In terms of the formatting of the x axis goes, I have this
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Format = "MMM.dd.yyyy HH:mm:ss";
chart1.Series["Series1"].XValueType = ChartValueType.DateTime;
I was wondering if there was a simple way to convert the point into a date/time value.
Thank you
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.
I have a chart and I want the user to see the values when the pointer is on the points.
By using digEmAll's help in the page finding the value of the points in a chart ,I could write the following code:
Point? prevPosition = null;
ToolTip tooltip = new ToolTip();
void chart1_MouseMove(object sender, MouseEventArgs e)
{
var pos = e.Location;
if (prevPosition.HasValue && pos == prevPosition.Value)
return;
tooltip.RemoveAll();
prevPosition = pos;
var results = chart1.HitTest(pos.X, pos.Y, false, ChartElementType.PlottingArea);
foreach (var result in results)
{
if (result.ChartElementType == ChartElementType.PlottingArea)
{
chart1.Series[0].ToolTip = "X=#VALX, Y=#VALY";
}
}
}
by the above code,the user can see the values when the pointer is near to a series.But now How can I let the user to see the values only when the pointer is on the points?
I replaced
int k = result.PointIndex;
if (k >= 0)
{
chart1.Series[0].Points[k].ToolTip = "X=#VALX, Y=#VALY";
}
instead of
chart1.Series[0].ToolTip = "X=#VALX, Y=#VALY";
to solve my problem.But It wasn't usefull.
You should modify the code in this way:
Point? prevPosition = null;
ToolTip tooltip = new ToolTip();
void chart1_MouseMove(object sender, MouseEventArgs e)
{
var pos = e.Location;
if (prevPosition.HasValue && pos == prevPosition.Value)
return;
tooltip.RemoveAll();
prevPosition = pos;
var results = chart1.HitTest(pos.X, pos.Y, false,
ChartElementType.DataPoint);
foreach (var result in results)
{
if (result.ChartElementType == ChartElementType.DataPoint)
{
var prop = result.Object as DataPoint;
if (prop != null)
{
var pointXPixel = result.ChartArea.AxisX.ValueToPixelPosition(prop.XValue);
var pointYPixel = result.ChartArea.AxisY.ValueToPixelPosition(prop.YValues[0]);
// check if the cursor is really close to the point (2 pixels around the point)
if (Math.Abs(pos.X - pointXPixel) < 2 &&
Math.Abs(pos.Y - pointYPixel) < 2)
{
tooltip.Show("X=" + prop.XValue + ", Y=" + prop.YValues[0], this.chart1,
pos.X, pos.Y - 15);
}
}
}
}
}
The idea is to check if the mouse is very close to the point e.g. 2 pixels around it (because is really unlikely to be exactly on the point) and show the tooltip in that case.
Here's a complete working example.
I would take this solution:
Add custom tooltip event handler:
this.chart1.GetToolTipText += this.chart1_GetToolTipText;
Implement event handler:
private void chart1_GetToolTipText(object sender, ToolTipEventArgs e)
{
// Check selected chart element and set tooltip text for it
switch (e.HitTestResult.ChartElementType)
{
case ChartElementType.DataPoint:
var dataPoint = e.HitTestResult.Series.Points[e.HitTestResult.PointIndex];
e.Text = string.Format("X:\t{0}\nY:\t{1}", dataPoint.XValue, dataPoint.YValues[0]);
break;
}
}
Consider the following as a possible better option than tooltips...use the label feature of the chart control.
DataPoint _prevPoint;
void chart1_MouseMove(object sender, MouseEventArgs e)
{
// this if statement clears the values from the previously activated point.
if (_prevPoint) {
_prevPoint.MarkerStyle = MarkerStyle.None;
_prevPoint.IsValueShownAsLabel = false;
}
var result = chart1.HitTest(e.X, e.Y, ChartElementType.DataPoint);
if (result.ChartElementType == ChartElementType.DataPoint)
{
var prop = result.Object as DataPoint;
if (prop != null)
{
prop.IsValueShownAsLabel = true;
prop.MarkerStyle = MarkerStyle.Star4;
}
}
}
I've tested this and i'm using it currently. It's very nice on charts with a lot of points since it shows the marker on the chart as well.