Reputation: 3563
I have a cupboard with 2 colliders - one for cupboard and one for it's box. When I press on the box, I want to open/close it. It worked fine, but now by some reason it only work when I press on the edge on the box. When click on the center, it don't work.
Video: https://youtu.be/OozsAi7KNzs
Here is the code, which play animation (open/close cupboard), when I press on the box:
public Animation[] animations;
public string[] animationName;
public bool playOneDirection; // should revert animation speed after second playing?
public AudioSource myAudioOpen;
public AudioSource myAudioClose;
private bool isDoorClosed;
private bool isAimationReadyToPlay = true;
private Collider thisCollider;
public void Start()
{
thisCollider = GetComponent<Collider>();
}
void Update ()
{
if (Input.GetButton("Fire1"))
if(DoPlayerLookAtButton() && isAimationReadyToPlay)
OpenCloseDoor();
}
bool DoPlayerLookAtButton()
{
RaycastHit _hit;
Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
bool isHit = Physics.Raycast(_ray, out _hit, 1.5f);
if (isHit && _hit.collider == thisCollider) return true;
else return false;
}
public void OpenCloseDoor()
{
if (!isDoorClosed) // Play animation with normal speed
{
myAudioOpen.Play();
for (int i = 0; i < animations.Length; i++)
{
animations[i][animationName[i]].speed = 1.0f;
animations[i].Play();
}
}
if(playOneDirection)
return;
if (isDoorClosed) // Play animation with revert speed
{
myAudioClose.Play();
for (int i = 0; i < animations.Length; i++)
{
animations[i][animationName[i]].speed = -1.0f;
animations[i][animationName[i]].time = animations[i][animationName[i]].length;
animations[i].Play();
}
}
StartCoroutine("DelayBetweenAnimations");
isDoorClosed = !isDoorClosed;
}
IEnumerator DelayBetweenAnimations()
{
isAimationReadyToPlay = false;
yield return new WaitForSeconds(0.5f);
isAimationReadyToPlay = true;
}
Upvotes: 2
Views: 269
Reputation: 23224
Your cupboard has 2 colliders, but you are only checking for one of them. If there is some kind of overlap then it could be fiddly to click the correct one. If you just want to be able to click anywhere on the game object change your code like so...
//From
//if (isHit && _hit.collider == thisCollider) return true;
//To
if (isHit && _hit.transform.gameObject == this.gameObject) return true;
Add a layer mask for your player and ensure your Physics.Raycast excludes that layer, to avoid the cast from hitting yourself. See here
Upvotes: 1
Reputation: 3563
I've made the main camera starting from the center of the player, so raycast hits player's collider. I made it trying to fix the bug when camera can go throuth the wall like on the screen below.
Raycast can be seen passing through the player and did not reach the box
Upvotes: 0