Hi,
I am trying to make player walk in the direction he/she is looking at in the Vive headset.
Before I put it into VR, I am using c# code that uses the mouse to control which direction the player is looking at and use “W” key to walk towards that direction and it works. After I transfer into the HTC Vive. The player can only move towards the left no matter which direction he/she is looking at inside the headset.
I have used three scripts to govern the movement and they are 1. Camera rotation 2. Movement Controller 3. HeadBobber
Script MovementController:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementController : MonoBehaviour
{
public float speed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.W))
{
this.transform.position += this.transform.localRotation * Vector3.forward * speed * Time.deltaTime;
}
}
}
Script CameraController:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public GameObject eye;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float rotationSpeed = 5.0f;
float mouseX = Input.GetAxis("Mouse X") * rotationSpeed;
float mouseY = Input.GetAxis("Mouse Y") * rotationSpeed;
this.transform.localRotation = Quaternion.Euler(x: 0, y: mouseX, z: 0) * this.transform.localRotation;
eye.transform.localRotation = Quaternion.Euler(x: mouseY * -1, y: 0, z: 0) * eye.transform.localRotation;
}
}
HeadBobber Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeadBobber : MonoBehaviour
{
public GameObject eye;
private float timer = 0.0f;
float bobbingSpeed = 0.18f;
float bobbingAmount = 2f;
float midpoint;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
midpoint = eye.transform.position.y;
float waveslice = 0.0f;
float vertical = Input.GetAxis("Vertical");
Vector3 cSharpConversion = transform.localPosition;
if(Input.GetKey(KeyCode.W))
{
waveslice = Mathf.Sin(timer);
timer = timer + bobbingSpeed;
if (timer > Mathf.PI * 2)
{
timer = timer - (Mathf.PI * 2);
}
}
else
{
timer = 0.0f;
}
if (waveslice != 0)
{
float translateChange = waveslice * bobbingAmount;
translateChange = vertical * translateChange;
cSharpConversion.y = midpoint + translateChange;
}
else
{
cSharpConversion.y = midpoint;
}
transform.localPosition = cSharpConversion;
}
}
Notice that in the hierarchy I have put my camera rig from steamvr under empty object player which contains all these script.
Your help would be so much appreciated. Thanks!