Box collider不会捕捉鼠标按键事件

时间:2016-08-08 07:25:30

标签: c# unity3d

我有一个带有2个碰撞器的橱柜 - 一个用于橱柜,一个用于它的盒子。当我按下盒子时,我想打开/关闭它。它工作得很好,但现在由于某种原因它只有当我按下盒子边缘时才能工作。点击中心时,它无法正常工作。

视频:https://youtu.be/OozsAi7KNzs

这是代码,当我按下框时播放动画(打开/关闭橱柜):

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;
}

2 个答案:

答案 0 :(得分:1)

你的橱柜有2个碰撞器,但你只是在检查其中一个。如果存在某种重叠,那么点击正确的重叠可能会很繁琐。如果你只想点击游戏对象的任何地方就可以改变你的代码...

//From
//if (isHit && _hit.collider == thisCollider) return true;
//To
if (isHit && _hit.transform.gameObject == this.gameObject) return true;

为您的播放器添加图层蒙版,并确保您的Physics.Raycast排除该图层,以避免演员阵容击中您自己。 See here

答案 1 :(得分:0)

我已经让主摄像头从播放器的中心开始,所以光线投射击中了玩家的对手。当相机可以像下面的屏幕一样走到墙上时,我试图修复这个错误。

可以看到Raycast通过播放器并没有到达盒子 enter image description here