I have to convert my pong game from keyboard usage to touch based mechanics. However I am completely stuck trying to figure out Unity's touch mechanics. I have searched through the internet and everyone somehow keeps resolving the issue in ways that are still failing for me. Here is, from everything I have gathered, what I believe should work. This is in my update method so it is constantly checking this.
Touch t;
void Update() {
if (Input.touchCount > 0) {
print("touch seen");
t = Input.GetTouch(0);
}
}
The if statement condition is never met no matter how many times I touch the screen. I am using a lenovo laptop that has a touch screen, maybe it is reading my touches as clicks? I just can't seem to figure it out. If I take away the if statement I get an ArrayIndexOutOfBounds Exception. Any help is extremely appreciated!
Update It is registering as a mouse click, and I can't just allow this because I need multiple touch inputs.
You can use Input.touchSupported to check if touch is supported on your computer. If it returns true, then read from touch with Input.GetTouch(0). If it returns false, then use Input.GetMouseButtonDown to read from the mouse instead. Touch won't work if your computer does not support touch screen. Below is complete code on how to do this:
void Update()
{
if (Input.touchSupported)
{
Debug.Log("TOUCH IS SUPPORTED");
if ((Input.touchCount > 0) && (Input.GetTouch(0).phase == TouchPhase.Began))
{
print("touched screen");
}
}
else
{
Debug.Log("TOUCH IS NOT SUPPORTED");
if (Input.GetMouseButtonDown(0))
{
print("clicked screen");
}
}
}
Related
I've been studying c sharp as part of my games course and my teacher has left and they cant find a replacement so I'm really struggling with coding my demo game. I’ve got a problem with my doors in my game and I was wondering if anyone knew how u can get it to work because I haven’t really got a clue when it comes to coding. Basically what I’ve got is my doors are shut then when I start my game they open and then shut but I need a code that will make sure it says shut until I’m in the trigger point but all the YouTube clips haven't been working and it says it’s got problems with it. I know what I want it to do I just don’t know how to put that into action.
This is my code but I don't think it does anything:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorAnimation: MonoBehaviour
{
Animator animator;
int isOpeningHash;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
animator = GetComponent<Animator>();
isOpeningHash = Animator.StringToHash("isOpening");
bool isOpening = animator.GetBool(isOpeningHash);
bool OpenPressed = Input.GetKey("e");
bool CloseDoor = Input.GetKey("left shift");
if (!isOpening && OpenPressed)
{
animator.SetBool(isOpeningHash, true);
}
if (isOpening && OpenPressed)
{
animator.SetBool(isOpeningHash, false);
}
}
}
First of all, make 2 animations(and turn off the loop or it will loop for eternity) for the opening and closing of door. Don't make Bools for the animator. It's basically useless. At the top of a script declare a bool called as open and set it equal to false(if the door is closed from start). Check if E is pressed and open is set to false(the door is closed), play the opening animation, set open to true and if left shift is pressed and open is set to true(the door is open) play the closing animation, set open to false. You can play animations if a certain key is pressed like this https://answers.unity.com/questions/1362883/how-to-make-an-animation-play-on-keypress-unity-ga.html
This should do your job :)
As the title says, I'm trying to enable/disable VR between different applications, and I need to do it as many times as I want.
I'm using Unity 2017.4 and SteamVR 2.0.1. I'm trying to do it with two different scenes of the same project (testing one in the editor, and launching the other as .exe).
This solution is not working, since apparently Actions and Poses are not handled correctly when VR is stopped with XRSettings.enabled = false.
Did anyone experienced the same behaviour?
I tried to find a workaround:
1) Disabling/enabling also Player and Hands
...
// ** ENABLE VR **
if (enable)
{
print("Enabling VR ...");
XRSettings.LoadDeviceByName("OpenVR");
yield return null;
print("Loaded device: " + XRSettings.loadedDeviceName);
XRSettings.enabled = enable;
EnablePlayerAndHands(true);
}
// ** DISABLE VR **
else
{
print("Disabling VR ...");
EnablePlayerAndHands(false);
XRSettings.LoadDeviceByName("");
yield return null;
print("Loaded device: " + XRSettings.loadedDeviceName);
XRSettings.enabled = false;
}
...
2) Added these lines in the SteamVR.cs file:
private void Dispose(bool disposing)
{
...
// added code
SteamVR_Input.initialized = false;
SteamVR_Behaviour.instance = null;
}
(In order to make it work, I had to add a public setter for the SteamVR_Behaviour.instance property).
3) In SteamVR_Behaviour, I added a check inside Update(), LateUpdate() and FixedUpdate():
if (_instance != null) ... // do update
These modifications won't fix the problems actually, because I still have some exceptions when I enable back VR, for example:
GetPoseActionData error (/actions/default/in/SkeletonLeftHand): InvalidHandle handle: 1152990670760182193
UnityEngine.Debug:LogError(Object)
Valve.VR.SteamVR_Action_Pose:UpdateValue(SteamVR_Input_Sources, Boolean) (at Assets/SteamVR/Input/SteamVR_Action_Pose.cs:96)
Valve.VR.SteamVR_Action_Skeleton:UpdateValue(SteamVR_Input_Sources, Boolean) (at Assets/SteamVR/Input/SteamVR_Action_Skeleton.cs:75)
Valve.VR.SteamVR_Input:UpdateSkeletonActions(SteamVR_Input_Sources, Boolean) (at Assets/SteamVR/Input/SteamVR_Input.cs:487)
Valve.VR.SteamVR_Input:UpdateSkeletonActions(Boolean) (at Assets/SteamVR/Input/SteamVR_Input.cs:462)
Valve.VR.SteamVR_Input:LateUpdate() (at Assets/SteamVR/Input/SteamVR_Input.cs:352)
Valve.VR.SteamVR_Behaviour:LateUpdate() (at Assets/SteamVR/Scripts/SteamVR_Behaviour.cs:224)
...but they are raised just a few times and then they stop. It could be due to some bad timing. Btw, I put an Interactable gameobject inside the empty scene just to test if I could still interact with it after disabling/enabling, and it seems that I can.
Still, I would expect some easier and cleaner method to achieve my goal. Am I missing something obvious or is it a bug from SteamVR newest version?
Thanks in advance for any help.
Please see this link for reference
https://docs.unity3d.com/ScriptReference/XR.XRSettings-enabled.html
Stopping a VR session is not supported in GearVR, not sure about SteamVR
Okay, so, I got the challenge to create a program, in Unity for GearVR.
I have to make a program which makes use of gaze input, so if you stare at an object for several seconds it'll display you a 360* video.
I barely can't find any GearVR Gaze Input tutorials around on the web so I wanted to give it a shot on Stackoverflow, and hopefully someone could help me out! :)
You have to use Physics.Raycast. This method emits a ray from the camera point to the camera orientation. You can use something like that:
// Does the Ray hit an object with a component named MyObjectScript?
RaycastHit hit;
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, out hit) )
{
var script = hit.transform.GetComponent<MyObjectScript>();
if (script != null)
{
//Do your stuff...
}
}
Simply put this script on your camera in the FixedUpdate method and another script named MyObjectScript in the object you want to detect.
Edit
Okay, so I partially solved the problem by adding a rigid body component to the capsule. I read somewhere that apparently you have to have one in order to move on the server.
Problem 2
The next problem I have is that I can now move a capsule that is spawned by the client fine and the host can move it as well as many times as they like. The problem I am getting now is that when the host spawns a capsule the client cannot move it at all and I get a sort of glitch effect on the client side and the capsule still doesn't move on the host side. Is there a reason why it would only work one way and not the other way around? I thought at first it might have to do with Spawn vs SpawnWithClientAuthority but that doesn't seem to make a difference.
Project Summary
I have a pretty simple multiplayer project, all I want to do is have one player host and the other join as a client. Once they are joined together the two players can spawn a capsule and then when the user clicks on a capsule. They should be able to pick it up and move it around the scene and the other player should be able to see this action. I can get both players to connect to the server and spawn their own capsule and both players can see this. The movement script is done as well. However, it is only transmitted on the host side. When the client picks up the object it does not update on the server.
Problem
I have done a bit of debugging and have found that when I call the command on the client it is not being executed at all through line breaks and simple debug statements.
Code
public void OnInputClicked(InputClickedEventData eventData)
{
Debug.Log("clicked");
if (isLocalPlayer)
{
if (Physics.Raycast(transform.position, direction: transform.forward, hitInfo: out hit, maxDistance: range))
{
Debug.Log("Hit capsule");
objectID = GameObject.Find(hit.transform.name);
objNetId = objectID.GetComponent<NetworkIdentity>();
CmdAssignAuthority(objNetId);
Debug.Log("Cmd done");
}
else
{
//else if the player is releasing the object we want to release authority
if (objNetId != null)
{
CmdAssignAuthority(objNetId);
}
}
}
[Command]
void CmdAssignAuthority(NetworkIdentity target)
{
Debug.Log("inside cmd");
NetworkConnection current = target.clientAuthorityOwner;
if (current != null && current != connectionToClient)
{
target.RemoveClientAuthority(current);
target.AssignClientAuthority(connectionToClient);
}
else
{
if (current != null)
{
target.RemoveClientAuthority(current);
}
if (current == null)
{
target.AssignClientAuthority(connectionToClient);
}
}
}
Question
Am I calling this command correctly? The script is attached to a player prefab and the capsule prefab contains a network id and a network transform. I am pretty new to Unet and this feels like a noob mistake.
How can I check internet connection inside Update Function in unity? I want to know whether the user is connected or not, and based on that just disable some functionality of my game.
Seems like there is no question like this been asked here before or if it is, it just checking the connection in Start function. Here is the code I have so far:
void Update () {
if (Application.internetReachability == NetworkReachability.NotReachable) {
Debug.Log ("No internet access");
} else {
Debug.Log ("internet connection");
}
}
#mjwills solution is right and it works OK, but nobody forces you to check connection every single frame of your game. You don't have to do that.
A better solution is to check connection when a button is clicked or when an event happens in your scene.
You need to run your Update function periodically.
http://unitylore.com/articles/timers-in-unity/ could be used for this:
using UnityEngine;
public class Timer : MonoBehaviour
{
public float waitTime = 1f;
float timer;
void Update ()
{
timer += Time.deltaTime;
if (timer > waitTime) {
if (Application.internetReachability == NetworkReachability.NotReachable) {
Debug.Log ("No internet access");
} else {
Debug.Log ("internet connection");
}
timer = 0f;
}
}
}
Unity's Application.internetReachability is not the best solution for internet detection as it was not designed for that purpose (as stated in the docs).
The proper way is to implement a technique called Captive Portal Detection, which is what all the major OS's use for their internet status detection. If implemented correctly, it can even detect when the network is restricted (hotels or airports) as it relies on HTTP requests of known content. Therefore it is far more reliable.
It is not that hard to implement. You need to make an HTTP request to a known "check page", and check whether the right content were returned.
However, if you want a complete, ready-to-use solution, you can check the asset Eazy NetChecker which I created for this purpose. It also has events and a custom editor. It is not free, but it is super cheap!