Hi we (myself and my students) are using MRTK in Unity to build simple VR games.
We are trying to get the xBox Controller to move the player (or in MRTK terms I think to move the scene around the camera which is fixed at 0,0,0).
I've set up the controller and played with the MRTK settings but no luck.
My controller works perfectly in Windows Mixed Reality Portal but goes dead when the game loads.
Any help on the exact steps/settings in the MRTK editor window is appreciated.
Ben
There are two things to solve here:
How to move the player. Answer: Use MixedRealityPlayspace.Transform.Translate
How to respond to gamepad input. Answer: you can use Unity's Input.GetAxis to figure out which buttons / joysticks are pressed, however I found it a bit easier to use the controller mappings in MRTK to map the "navigation action" to the gamepad dpad and joysticks, and then listen for input changed on navigation events.
You can use the following code to move the MR Playspace using gamepad:
using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.Utilities;
using UnityEngine;
/// <summary>
/// Moves the player around the world using the gamepad, or any other input action that supports 2D axis.
///
/// We extend InputSystemGlobalHandlerListener because we always want to listen for the gamepad joystick position
/// We implement InputHandler<Vector2> interface in order to receive the 2D navigation action events.
/// </summary>
public class MRPlayspaceMover : InputSystemGlobalHandlerListener, IMixedRealityInputHandler<Vector2>
{
public MixedRealityInputAction navigationAction;
public float multiplier = 5f;
private Vector3 delta = Vector3.zero;
public void OnInputChanged(InputEventData<Vector2> eventData)
{
float horiz = eventData.InputData.x;
float vert = eventData.InputData.y;
if (eventData.MixedRealityInputAction == navigationAction)
{
delta = CameraCache.Main.transform.TransformDirection(new Vector3(horiz, 0, vert) * multiplier);
}
}
public void Update()
{
if (delta.sqrMagnitude > 0.01f)
{
MixedRealityPlayspace.Transform.Translate(delta);
}
}
protected override void RegisterHandlers()
{
CoreServices.InputSystem.RegisterHandler<MRPlayspaceMover>(this);
}
protected override void UnregisterHandlers()
{
CoreServices.InputSystem.UnregisterHandler<MRPlayspaceMover>(this);
}
}
I used the following controller mapping to have dpad and thumbstick hook up to the navigation action:
Then I created a new gameobject, attached the MRPlayspaceMover script, and assigned the "navigation action" field:
Related
So, here's my error! im designing a FPS game in unity and im scripting an AI enemy (for now it just moves around randomly) im also using NeoFPS that should be all the background info out of the way as for whats happening:
i can see the enemy in scene view and i can see it in the game view before i press play, when i do press play the enemy disappears in game view but i can still see it trying to move around the little box i put it in and stuff of the sorts via navmesh etc. the collider for the enemy is still there when i go into the box however i cant see it and i shoot through it and do no damage to it whatsoever i will include screenshots and my AI code below (the white capsule is the enemy w AI script inside a little box, the camera is the FPS player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AICharacterController : MonoBehaviour
{
private NavMeshAgent m_Agent;
private void Awake()
{
m_Agent = GetComponent<NavMeshAgent>();
}
Vector3 movePosition;
void Update()
{
if (movePosition == Vector3.zero
|| Vector3.Distance(transform.position, m_Agent.destination) < 1)
{
SelectNewDestination();
}
}
void SelectNewDestination()
{
Vector2 pos = Random.insideUnitCircle * 50;
movePosition.x = pos.x;
movePosition.y = pos.y;
NavMeshHit hit = default;
if (NavMesh.SamplePosition(movePosition, out hit, 4, NavMesh.AllAreas))
{
m_Agent.SetDestination(hit.position);
}
}
public void Die()
{
Destroy(gameObject, 0.25f);
}
}
(if you dont see an image below then stackoverflow replaced it with a link and its not working)
If things are invisible in a camera, but not in the scene view then that means that the "Culling Mask" property on the camera is set to ignore the layers the object is on. NeoFPS uses a spawning system, so its quite possible that the camera in the character that's spawned has a different culling mask setup to the camera in the scene that you're looking through outside of play mode. To fix that you would have to find the camera in the character prefab's hierarchy (usually called PlayerCameraSpring) and add your AI's layer to its culling mask.
I make a game for android and i need to have UI Joystick and UI Attack Button on the game screen. I already have the workable Joystick and Attack Button on Space key for keyboard.
Can someone told me how should i switch code from keyboard Input to Touch Input?
P.S. i'm sorry for my english.
if (Time.time >= nextAttackTime)
{
if (Input.GetKeyDown(KeyCode.Space))
{
Attack();
nextAttackTime = Time.time + 2.5f / attackRate;
}
}
try this one.
using UnityEngine;
using UnityEngine.UI;
public class Example : MonoBehaviour
{
//Make sure to attach these Buttons in the Inspector
public Button YourButton,
void Start()
{
YourButton.onClick.AddListener(TaskOnClick);
}
void TaskOnClick(){ /// this method will active when press the button
if (Time.time >= nextAttackTime)
{
Attack();
nextAttackTime = Time.time + 2.5f / attackRate;
}
}
}
Another way would be to work with the unity Button script, apply it to the GameObject that represents the Button. Under Target Graphic add the corresponding Object with the graphic. Under On Click() add an Event, put the gameobject that has your Attack Function in (None Object) and add the Attack function under Function.
here are some infos about how the button works:
https://docs.unity3d.com/2018.3/Documentation/Manual/script-Button.html
edit: was also answered here Unity Button code not working
Game View- Camera Display
When I click the Space Bar for the player to jump, the Display drop down menu pops up and the player doesn't jump. However, the player can move upon all key presses.
Here's the information that I have:
1) Everything worked and functioned properly.
2) I added a health bar to my boss.
3) I created a second canvas (First canvas was for my Player's HP).
4) I made the Boss HP bar render mode: World Space.
5) I attached the canvas to the boss controller in the hierarchy as a child.
6) The code I use for Player Jump is Input.GetKeyDown(KeyCode.Space).
7) The mouse curser is inside the Game View whilst testing the SpaceBar Jump.
8) I'm developing in Unity 2018 5.3 2D mode.
Official Question('s):
1) Why does the Spacebar causing the camera display drop menu to appear?
2) How do I fix this?
Edit / Additional Content:
Here's my Jump script
public float jump1 = 5.0f;
private bool onGround;
//private bool dblJump; //Not implemented yet
public Rigidbody player;
void Start () {
player = GetComponent<Rigidbody>();
onGround = true;
}
// Update is called once per frame
void Update () {
if (onGround == true) {
if (Input.GetKeyDown(KeyCode.LeftShift))// KeyCode.Space
{
player.velocity = new Vector3(0, jump1, 0);
onGround = false;
// Debug.Log("The onGround is False");
}
}
}
Keep in mind that I have temporarily changed my jump to LeftShift. However, my problem persist with the space bar, even when I click it with left shift as my jump. SpaceBar seems to summon the drop down menu for the camera display. (I can't seem to catch the drop down menu with a screen shot because it goes away upon a click)
Also Note - I'm inside a class called PlayerJump : MonoBehavior.
It seems like it's a known issue with some versions of Unity 5.3, I have a few solutions you can try :
Drag you game window somewhere else in the editor
Enable the "Maximise on play" button
Attach this script to your drop-down element :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DropdownScript : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
void Start()
{
dropDown = GetComponent<Dropdown>();
dropDown.interactable = false;
}
public void OnPointerEnter(PointerEventData ped)
{
dropDown.interactable = true;
}
public void OnPointerExit(PointerEventData ped)
{
dropDown.interactable = false;
}
}
Otherwise update you Unity version if it's not the latest release? I am not experiencing this issue but many other users are apparently.
I'm trying to follow the instructions in the unity documents how to use Inverse Kinematics in this page:
Inverse Kinematics
But i don't have the IK Animator Controller when i select Controller for the Animator.
I tried adding the script now. But the hand the right hand is folded to the other side. It's not like it's holding the flash light: The script is attached to the ThirdPersonController. And i dragged to the script in the Inspector to the rightHandObj the EthanRightHand and to the lookObj i dragged the Flashlight.
But the hand seems to be wrong way.
This is the script i'm using now the IKControl:
using UnityEngine;
using System;
using System.Collections;
[RequireComponent(typeof(Animator))]
public class IKControl : MonoBehaviour
{
protected Animator animator;
public bool ikActive = false;
public Transform rightHandObj = null;
public Transform lookObj = null;
void Start()
{
animator = GetComponent<Animator>();
}
//a callback for calculating IK
void OnAnimatorIK()
{
if (animator)
{
//if the IK is active, set the position and rotation directly to the goal.
if (ikActive)
{
// Set the look target position, if one has been assigned
if (lookObj != null)
{
animator.SetLookAtWeight(1);
animator.SetLookAtPosition(lookObj.position);
}
// Set the right hand target position and rotation, if one has been assigned
if (rightHandObj != null)
{
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1);
animator.SetIKRotationWeight(AvatarIKGoal.RightHand, 1);
animator.SetIKPosition(AvatarIKGoal.RightHand, rightHandObj.position);
animator.SetIKRotation(AvatarIKGoal.RightHand, rightHandObj.rotation);
}
}
//if the IK is not active, set the position and rotation of the hand and head back to the original position
else
{
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 0);
animator.SetIKRotationWeight(AvatarIKGoal.RightHand, 0);
animator.SetLookAtWeight(0);
}
}
}
}
Add an empty game object to the flashlight and target that instead of the flashlight object itself. Hit play and then fiddle with the placement of the empty object until it is where you want it. Then just turn the flashlight into a prefab, stop play mode and make sure the flashlight in the scene matches the prefab (you can just use revert to do that if needed).
Now it would be doing exactly what you want every time. You could even have multiple prefabs with the empty object positioned differently to allow characters with larger or smaller hands to hold it convincingly.
I try to create a VR scene in unity using google cardboard sdk. I add a cube and CardboardMain.prefab to scene. There is an example scene that detect focus on cube. Its hierarchy view is :
I don't know how to add GUIReticle object or prefab like as the image.
How can I detect focus on an object?
Actually you could make the script by your own and it is quite simple.
You could detect whether the user is looking at your object or not by using RayCast from the Main Camera. If the RayCast hit your object, then it is being focused on.
For example:
using UnityEngine;
using System;
[RequireComponent(typeof(Collider))]
public class LookableObject : MonoBehaviour {
[SerializeField]
Transform cam; // This is the main camera.
// You can alternately use Camera.main if you've tagged it as MainCamera
bool focus; // True if focused
Collider gazeArea; // Your object's collider
public void Start () {
gazeArea = GetComponent<Collider> ();
}
public void Update () {
RaycastHit hit;
if (Physics.Raycast (cam.position, cam.forward, out hit, 1000f)) {
focus = (hit.collider == gazeArea);
} else {
focus = false;
}
}
}
Edit: This is just an example. You probably would want to make a script to do the Raycast only just once instead of doing the Raycast on each of your object over and over again to make your project runs faster.