Unity3D-ray inspection

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/q943520218/article/details/102709111

   In the third-person game, mouse click on the screen, move to the designated location role is an important feature.

   This is generally achieved by ray detector

   The principle is: first sends a ray from the main camera on the screen, after hitting the ground, the character moves to the appropriate location

   Code is implemented as follows:

    bool GetInteraction()
    {
        Ray interactionRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit interactionInfo;
        if(Physics.Raycast(interactionRay, out interactionInfo, Mathf.Infinity))
        {
            GameObject interactedObject = interactionInfo.collider.gameObject;

            if (!walkBackward || swordWalking > 0 )
            {
                gameObject.transform.LookAt(interactionInfo.point); // 移动
            }
            else
            {
                gameObject.transform.rotation = Quaternion.LookRotation(gameObject.transform.position - interactionInfo.point); // 旋转
            }

            return true;
        }

        touchPosition = null;
        return false;
    }

 

Guess you like

Origin blog.csdn.net/q943520218/article/details/102709111