Unity game processing in the third-person camera occlusion

In the game development process will inevitably make a third-person game if the terrain is more facility
or in the game room is likely to make us a good perspective will be adjusted in the wall blocking the course of the game the main character
such a sense of the game experience will be great discount

Like this (cover half of the body can still sometimes may cover the entire player)Here Insert Picture Description

This blog to introduce a method to let the camera automatically adjust to the proper angle (slow)

The idea is that we are in a position above the adjusted camera angles and the players on the
middle set up multiple cameras position
and then slowly realized automatically adjusted by interpolation

As for how we use automatic adjustment rays to achieve
our hair out camera-ray detector ray collides with an object tag, if not the player (obscured) to change to the next position
Here Insert Picture Description

 private Vector3 offset;//偏移量

    private Transform Player;

    private void Start()
    {
        Player = GameObject.FindGameObjectWithTag("Player").transform;
        offset = transform.position - Player.position;
        offset = new Vector3(0, offset.y, offset.z);
    }

    private void Update()
    {

        Vector3 BeginPos = offset + Player.position;

        Vector3 EndPos = offset.magnitude * Vector3.up + Player.position;//正上方的坐标

        Vector3 pos1 = Vector3.Lerp(BeginPos, EndPos, 0.25f);
        Vector3 pos2 = Vector3.Lerp(BeginPos, EndPos, 0.5f);
        Vector3 pos3 = Vector3.Lerp(BeginPos, EndPos, 0.75f);


        Vector3[] posArray = new Vector3[] { BeginPos, pos1, pos2, pos3, EndPos };

        Vector3 TargetPos = posArray[0] ;//合适的位置

        RaycastHit hit;
        for(int i = 0; i < 5; i++)
        {
            if(Physics.Raycast(posArray[i],Player.position -posArray[i],out hit))
            {
                if (hit.collider.tag != "Player")
                {
                    //碰撞到别的物体 (被挡住)
                    continue;
                }
                else
                {
                    TargetPos = posArray[i];
                    break;
                }
            }
        }
        //transform.position =TargetPos;

        transform.position = Vector3.Lerp(transform.position, TargetPos, Time.deltaTime);
        transform.LookAt(Player);

    }

The script I used an array of Vector3
note of the initial setting, otherwise there will be strange BUG strange position because some may not meet all of the conditions back to the initial position

This will some nook and cranny of the camera will automatically switch to the appropriate perspective

Here Insert Picture Description

If you are concerned about the unity lovers my blog I will continue to update my blog

Published 56 original articles · won praise 53 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44302602/article/details/104067697