简体   繁体   中英

Trying to hit Box Collider with Raycast

I am trying to play an animation after clicking by mouse click on a box collider which is on a prefab named "TorObjekt", but nothing happens the animation isn't playing neither the debug.log.

Would someone be able to help me please?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Tor : MonoBehaviour
{
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {

            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.transform.gameObject.name == "TorObjekt")

                    GetComponent<Animator>().SetTrigger("Tor");
                Debug.Log("Hello?");
                Destroy(hit.collider.GetComponent<BoxCollider>());
            }
        }

    }
}

The problem might be that you need the game object you are trying to hit to have a rigidBody. If this doesn't work or it already does, try using Debug.DrawRay to draw your ray and make sure it's hitting the object.

I would check these things:

1.- That the ray is thrown correctly. I think that you need to set the camera as the origin of the ray, so that its thrown from where you are (you are the camera) to your object. Find this helper script that draws the rays in the scene to check if they're thrown correctly.

public class click : MonoBehaviour {
    void Update() {
        if (Input.GetMouseButtonDown(0)) {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            Debug.DrawRay(ray.origin, ray.direction * 20, Color.white);
            if (Physics.Raycast(ray, out hit)){
                if (hit.collider != null) {
                    Debug.Log("hit!");
                }
                else {
                    Debug.Log("no hit");
                }
            }
        }
    }
}

2.- Check that the target has a collider, that it is enabled and that there is nothing wrong with the layers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM