I have a script to grab objects but it has alittle problem. can anyone check it?
Hello all. i have managed to get this from a tutorial and make it work for the oculus using OVRInput for the xbox buttons. It works for the most part, except if there are 2 or more objects within the range distance...it will grab all of them. HOw would i change it so that it only grabs the one I'm facing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrabThrowObject : MonoBehaviour {
public Transform player;
public Transform playerCam;
public float throwForce = 10;
bool hasPlayer = false;
bool beingCarried = false;
public AudioClip[] soundToPlay;
private AudioSource audio;
public int dmg;
private bool touched = false;
// Use this for initialization
void Start () {
audio = GetComponent<AudioSource> ();
}
// Update is called once per frame
void Update () {
float dist = Vector3.Distance (gameObject.transform.position, player.position);
if (dist <= 2.5f) {
hasPlayer = true;
Debug.Log ("Able to grab");
}
else{
hasPlayer = false;
}
//Grab object. Bug is you can grab 2 or even 3 if in range
if (hasPlayer && OVRInput.GetDown (OVRInput.Button.One) ) { //Press A button
GetComponent<Rigidbody> ().isKinematic = true;
transform.parent = playerCam;
beingCarried = true;
Debug.Log ("Pressed A to grab");
}
if( beingCarried)
{
if (touched) {
GetComponent<Rigidbody> ().isKinematic = false;
transform.parent = null;
touched = false;
}
if (OVRInput.GetDown (OVRInput.Button.Three ) ) {//Press X
GetComponent<Rigidbody> ().isKinematic = false;
transform.parent = null;
beingCarried = false;
GetComponent<Rigidbody> ().AddForce (playerCam.forward * throwForce);
RandomAudio ();
}
else if(OVRInput.GetDown(OVRInput.Button.Two)){ //Press B button to drop object
GetComponent<Rigidbody>().isKinematic = false;
transform.parent = null;
beingCarried = false;
}
}
}
void RandomAudio(){
if (audio.isPlaying) {
return;
}
audio.clip = soundToPlay [Random.Range (0, soundToPlay.Length)];
audio.Play ();
}
void OnTriggerEnter(){
if (beingCarried) {
touched = true;
}
}
}
