- Home /
Physics.CheckSphere always returns true when it shouldn't
Basically the title, I am fairly new to unity, and i wanted to create a simple trigger that moves the dummy of an endtable. When the player goes in, it should ring true, and then the rest the code will work. Problem is, is that it always returns true. Any help on this one would be greatly appreciated.
public class OpenCabinent : MonoBehaviour {
public GameObject PlayerPtr;
public SphereCollider SphereCollide;
public float DrawerOffset;
public GameObject Cabinet;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Physics.CheckSphere(PlayerPtr.transform.position, SphereCollide.radius) == true)
{
Debug.Log(Physics.CheckSphere(PlayerPtr.transform.position, SphereCollide.radius) == true);
//this will move the cabinent back to its begining position
if(Input.GetKey(KeyCode.E) == true)
{
if(Cabinet.transform.localPosition.z >= 2.148298)
{
Cabinet.transform.Translate(0,DrawerOffset * Time.deltaTime,0); //* Time.deltaTime);
}
}
//this will move tha cabinent out, until it hits a certain number
if(Input.GetKey(KeyCode.Q) == true)
{
if(Cabinet.transform.localPosition.z <= 2.776)
{
Cabinet.transform.Translate(0,-DrawerOffset* Time.deltaTime,0); //* Time.deltaTime);
}
}
}
}
}
Try using OverlapSphere(), then looping over the results, to see what you're "accidentally" hitting.
Collider[] hits = Physics.OverlapSphere(center, radius);
for (int i=0; i<hits.Length; i++) Debug.Log( hits[i].gameObject.name );
I can see a bit of the problme, that debug statement is never called at all, so could it be my code implementation, or where I put the sphere collide as a trigger?
Answer by Vicarian · Dec 27, 2016 at 02:51 PM
If you want functionality to be enabled when the player enters a particular space, you could set up a region using a primitive (such as the referenced Sphere Collider), set its collider state to IsTrigger, then listen for OnTriggerEnter on the script. Set a boolean to true on enter, and false on OnTriggerExit. Then you check that bool before checking the Input in Update.
bool canInteract;
void Update() {
if (canInteract)
{
if(Input.GetKey(KeyCode.E) == true)
{
if(Cabinet.transform.localPosition.z >= 2.148298)
{
Cabinet.transform.Translate(0,DrawerOffset * Time.deltaTime,0); //* Time.deltaTime);
}
}
//this will move tha cabinent out, until it hits a certain number
if(Input.GetKey(KeyCode.Q) == true)
{
if(Cabinet.transform.localPosition.z <= 2.776)
{
Cabinet.transform.Translate(0,-DrawerOffset* Time.deltaTime,0); //* Time.deltaTime);
}
}
}
}
void OnTriggerEnter (Collider other)
{
canInteract = true;
}
void OnTriggerExit (Collider other)
{
canInteract = false;
}