Record: Writing Unity Scripts 9.0

Table of contents


I suddenly realized that I didn’t seem to have written anything about rays, so I said why I always felt like something was missing (feeling guilty)
Let’s write about rays here. The function of ray detection and mouse click will be implemented here.

Rays

Ray is a method of detecting colliders or triggers in Unity, which can be used to achieve some interactive effects, such as mouse clicks on objects, shooting games, ray tracing, etc. The ray needs to have a starting point and a direction, and can be created through code or emitted from the camera using the Camera.main.ScreenPointToRay method. The results of ray detection can be obtained through the RaycastHit structure, including collision points, collision objects, collision normals and other information. Ray detection can also specify detection levels, distances, angles and other parameters to improve performance and accuracy.

Collision detection can help us achieve functions such as automatically triggering the plot when arriving at a certain location, determining whether a bullet hits the player, etc. But if I want to achieve, for example, when the mouse is hovering over a character, the character information will automatically pop up, how should I judge? At this time, use collision detection to generate a transparent collision body from the camera and move towards the character. When it collides with the character, the character information will pop up? Wouldn't it be too cumbersome? Maybe you will also think, if I directly generate a long enough transparent collision body, can the pop-up information logic of the character be triggered at the moment of creation? Yes, this can indeed be done, and this is the ray! It just turns an infinitely long transparent collider into an infinitely long line, that's all.

some preparations

Create a new object (or object? Anyway, it’s something similar) so that the camera, which is the MainCamera, can see it and we can touch it. After all, we need a visible object to emit rays to achieve what we want. As a result, add a rigid body component to this object (otherwise, how to perform collision detection?)
Insert image description here

Write code

private void learnRay()
{
    if (Input.GetMouseButtonDown(0))
    {
        //创建一道射线
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //检测射线
        if (Physics.Raycast(ray,out RaycastHit hitInfo))
        {
            //hitInfo.transform.Translate(transform.up * 10);
            //Debug.Log(hitInfo.transform.name);
            //rb.AddForce(transform.up * 500);
            //Debug.Log(hitInfo.transform.name);
            //Debug.Log(hitInfo.point);
            //hitInfo.point;   //射线撞击点

            GameObject shell = Instantiate(Sphere,transform.position+transform.right*offset,transform.rotation);
            shell.GetComponent<Rigidbody>().velocity = Vector3.Normalize(hitInfo.point - transform.position) * 20;
            // 计算小球的动量
            //Vector3 ballMomentum = shell.GetComponent<Rigidbody>().velocity * shell.GetComponent<Rigidbody>().mass;
            // 给物体施加一个与小球相反方向的同等大小的力,抵消小球的反作用力
            //rb.AddForce(-ballMomentum, ForceMode.Impulse);
        }
        
    }
}

Collision detection is also indispensable

//碰撞检测的方法
private void OnCollisionEnter(Collision collision)//碰撞发生时
{
    //Destroy(collision.transform.gameObject);
    Debug.Log("刚碰到");
}
private void OnCollisionExit(Collision collision)//碰撞结束时
{
    Debug.Log("碰完了");
}
private void OnCollisionStay(Collision collision)//正在碰撞时
{
    Debug.Log("");
}
private void OnTriggerEnter(Collider other)
{
    Debug.Log("进来");
}
private void OnTriggerStay(Collider other)
{
    //Debug.Log("other.transform.name");
    //rb.AddForce(transform.up * 50);
    rb.AddForce(transform.up*10);
    
}
private void OnTriggerExit(Collider other)
{
    Debug.Log("run");
}

Of course, in this script, the method used is to prepare a prefab in advance, which is the "Sphere" in the code, so at the same time, a prefab needs to be prepared in advance. It doesn't matter what it is, but it must correspond to the code, otherwise it will appear. some unforeseen problems

Run the script after mounting it

Insert image description here
Whenever the mouse is clicked, a ray will be triggered, copying the prefab to emit a small ball.

Guess you like

Origin blog.csdn.net/m0_72471315/article/details/134709313