简体   繁体   English

如何使相机不是 go 穿过 Unity3d 中的墙壁和物体?

[英]How to make camera not go through the walls and objects in Unity3d?

I am creating a third-person android 3d game in unity.我正在统一创建第三人称 android 3d 游戏。 I have set up a free look on touch script to move the camera view around the player.我已经设置了一个免费的触摸脚本来移动播放器周围的相机视图。 Below is the code.下面是代码。 But the camera following my player is moving through the walls and objects coming in between the player and the camera.但是跟随我的玩家的摄像机正在穿过墙壁和进入玩家和摄像机之间的物体。 I want the camera to adjust itself if it bumps into an object (Camera is not a child of my player).如果相机撞到 object(相机不是我的播放器的孩子),我希望相机自行调整。 Things I have tried but did not work:我尝试过但没有奏效的事情:

  1. Applying a box collider/rigidbody/material to the camera将盒子对撞机/刚体/材质应用到相机

  2. Making an empty gameobject parent of camera and applying box collider/rigidbody/material to that gameobject制作相机的空游戏对象父级并将盒子碰撞器/刚体/材质应用于该游戏对象

  3. Making the camera clipping angle (near) < 0.3 This only works for 1st person but not for 3rd person.使相机剪辑角度(近)< 0.3 这仅适用于第一人,但不适用于第三人。

I guess raycasting can be of help but I don't know how to implement it.我想光线投射会有所帮助,但我不知道如何实现它。 Any suggestion would be of great help!任何建议都会有很大帮助!


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.ThirdPerson;

public class ThirdPersonInput : MonoBehaviour
{ 
    public FixedJoystick LeftJoystick;
    public FixedButton Button;
    public FixedTouchField TouchField;

    protected ThirdPersonUserControl Control;
    protected float CameraAngle;
    protected float CameraAngleSpeed = 0.2f;
    // Start is called before the first frame update
    void Start()
    {
        Control = GetComponent<ThirdPersonUserControl>();
    }
    // Update is called once per frame
    void Update()
    {
        Control.m_Jump = Button.Pressed;
        Control.Hinput = LeftJoystick.Direction.x;
        Control.Vinput = LeftJoystick.Direction.y;

        CameraAngle += TouchField.TouchDist.x * CameraAngleSpeed;

        Camera.main.transform.position = transform.position + Quaternion.AngleAxis(CameraAngle, Vector3.up) * new Vector3(0, 3, -3);
        Camera.main.transform.rotation = Quaternion.LookRotation(transform.position + Vector3.up * 2f - Camera.main.transform.position, Vector3.up);
    }
} 

It would be much convenient if you tried using cinemachine.如果您尝试使用cinemamachine,那将非常方便。 Inside the cinemachine, there is a component called Cinemachine collider.在电影机内部,有一个名为 Cinemachine collider 的组件。 Which will help you to solve this issue.这将帮助您解决此问题。 Also, there are a bunch of other features to try.此外,还有许多其他功能可供尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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