I’m creating a snowball fight game for the HTC Vive. When the controller is placed into a snow pile a snowball should be spawned in the same position as the controller - this is held whilst the trigger is held. When the trigger is released the snowball should be thrown/dropped (depending on the movement of the controller).
However, the snowball spawns a few feet away from the controllers position (still affected by the movement of the controller as it should be). Also, when the trigger is released it should be thrown/affected by gravity however instead just stays in the same place as when the trigger was released… The snowball’s rigidbody does change to use gravity = true and isKinematic = false though. Can anyone help with either issue pleeeeeease?
Here’s the code:
public class ThrowSnowball : MonoBehaviour {
private Valve.VR.EVRButtonId triggerButton = Valve.VR.EVRButtonId.k_EButton_SteamVR_Trigger;
private SteamVR_TrackedObject trackedObj;
private SteamVR_Controller.Device device;
public GameObject Snowball;
Rigidbody sbrb;
private GameObject collided;
private bool sb = false;
private GameObject Spawning;
public Transform controller;
void Awake()
{
trackedObj = GetComponent<SteamVR_TrackedObject>();
sb = false;
Debug.Log("sb = false");
}
private void OnTriggerEnter(Collider collider)
{
Debug.Log("Entered snow pile");
collided = collider.gameObject;
}
private void OnTriggerExit(Collider other)
{
Debug.Log("Exited snow pile");
collided = null;
}
private void Update()
{
device = SteamVR_Controller.Input((int)trackedObj.index);
if (sb == false && device.GetPressDown(triggerButton) && collided != null)
{
Debug.Log("Trigger Pressed");
Spawning = Instantiate(Snowball, transform) as GameObject;
sbrb = Snowball.GetComponent<Rigidbody>();
sbrb.isKinematic = true;
sbrb.useGravity = false;
Spawning.gameObject.transform.SetParent(transform);
sb = true;
Debug.Log("sb = true");
}
if (device.GetPressUp(triggerButton) && sb == true)
{
Debug.Log("Let go of trigger");
sbrb.isKinematic = false;
sbrb.useGravity = true;
Spawning.gameObject.transform.SetParent(null);
sb = false;
Debug.Log("sb = false");
ThrowSB(sbrb);
}
}
void ThrowSB(Rigidbody sbrb) {
Transform origin = trackedObj.origin ? trackedObj.origin : trackedObj.transform.parent;
sbrb.velocity = device.velocity;
sbrb.angularVelocity = device.angularVelocity;
}
}