Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by abhijit93 · Mar 21, 2016 at 09:58 AM · collidercamera-movementrigidbody-collisionterraincollider

Camera passing through terrain. Please help

I am trying to create a simple walkthrough using the MainCamera. And I've added simple script to move the camera, using transform.Translate. Problem I'm facing is, the camera passes right through the terrain, trees and what not. I've added the rigidBody component to the camera and with gravity on, the camera falls right through the terrain (has a terrain collider). Also tried Sphere collider to the camera and didn;t work. Not able to figure out the problem. Please help and thanks in advance.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by Rajeesh_AR · Mar 21, 2016 at 11:36 AM

Hi @abhijit93

You could add the camera to a 3d gameobject (put the cam inside GameObject). then add the Rigidbody to that GameObject. It will not fall through the Terrain

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image abhijit93 · Mar 21, 2016 at 02:44 PM 0
Share

Hi @Rajeesh_AR

Thank you so much. Tried exactly what you told and it worked like a charm. Just increased the angular drag to remove the backward movement, but Thanks for your reply.

Solution this simple, but struggled 4 days on this. Hahaa. Cheers

avatar image GermiyanBey · Sep 12, 2018 at 05:47 PM 0
Share

Ins$$anonymous$$d of adding camera into a 3D Object, simply add Rigidbody and Sphere Collider to Camera. This can be simpler. (Rigidbody: without gravity, freeze rotation X and Z also from constraints)

avatar image
0

Answer by GermiyanBey · Dec 16, 2019 at 02:20 PM

I found another solution for anyone needing. Previously I had suggested putting Rigidbody and Sphere Collider to Camera (Collider has Trigger, Rigidbody is without gravity, freeze rotation X and Z from the constraints too) But still the camera enters to terrain if player insists to go down the terrain and it clips the terrain (I changed terrain thickness to great numbers, still "sometimes" camera was entering into terrain.

So I developed another solution on the below, this minimizes passing through terrain very much.

Notes: The bottom part is your Mouse Scroll code, and the rest of the script is to limit the camera going below Terrain. I left comments above each section. Please make sure to add Sphere Collider (with Trigger on) and Rigidbody as I mentioned on the above message of mine. Then apply the script below.

Also I considered the Terrain has "Terrain" tag, change it if you use something else, but make sure your Terrain has a tag.

     [Tooltip("The time to move Cam away from Terrain")]
     public float smoothTime = 0.1f; //Make it 0.1f, 0.3f, 1f or any number according to your preference. This defines movement speed of cam if cam collides with terrain. Smaller number means quicker movement.  
     [Tooltip("The min permitted Height limit between Cam and Terrain")]
     public float minCamTerrainHeight = 0.15f;
     [Tooltip("Raycast height from the Cam to Terrain")]
     public float terrainDetectionHeight = 2f;
     public float zoomSpeed = 350f;
     private Vector3 velocity = Vector3.zero; 
     private bool colliding = false;

 void  OnTriggerEnter (Collider other){ 
     if (other.gameObject.CompareTag("Terrain"))
         colliding = true; 
 }

 void  OnTriggerExit (Collider other){ 
     if (other.gameObject.CompareTag("Terrain"))
         colliding = false; 
 }
 
         //If Camera collides with Terrain, move the camera smoothly above the terrain
         if (colliding){ 
             transform.localPosition = Vector3.SmoothDamp(transform.localPosition, new Vector3(0,minCamTerrainHeight,0), ref velocity, smoothTime); 
         }
 
         //Check Distance between Terrain-Camera object
         RaycastHit hit;
         if(Physics.Raycast(transform.position, -transform.up, out hit, terrainDetectionHeight)) {
             //If the camera is at a certain height above the Terrain, limit Mousescroll going down further but don't limit it going up:
             if(hit.collider.tag=="Terrain"){  
                 print("Camera is very close to Terrain.");
                 float moveDown = Input.GetAxis("Mouse ScrollWheel");
                 if (moveDown < 0)
                     transform.Translate(new Vector3(0, moveDown) * Time.deltaTime * -zoomSpeed, 0);
             }
         }
         else
             //move the camera when you scroll. This happens if it is above the terrainDetectionHeight.
             transform.Translate(new Vector3(0, Input.GetAxis("Mouse ScrollWheel")) * Time.deltaTime * -zoomSpeed, 0);
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by GXMark · Jun 27, 2021 at 09:59 PM

Here is a basic camera follow script for

  1. Smooth zoom

  2. Ground detection moving closer to the player until the raycast is above the ground.

       // Main
         public bool cameraEnabled = false;
         public float cameraTargetHeight = 1.5f;
         public float mouseSensitivity = 3f;
         public float lerpSpeed = 15f;
    
         // Zoom
         public float zoomSensitivity = 5;
         public float zoomStartDistance = 2;
         public float zoomMin = 1.5f;
         public float zoomMax = 20;
    
         // Ground Collision
         public float maxCollisionDetectionDistance = 0.5f;
         public float collisionCorrectionIncrement = 0.2f;
     
         private float x = 0.0f;
         private float y = 0.0f;
         private float distance = 3.0f;
         private float currentDistance = 3.0f;
    
         void Start()
        {
            distance = zoomStartDistance;
            currentDistance = zoomStartDistance;
        }
    
            void LateUpdate()
             {
                 if (!cameraEnabled)
                     return;
         
                 if (Input.GetMouseButton(1))
                 {
                     x += Input.GetAxis("Mouse X") * mouseSensitivity;
                     y -= Input.GetAxis("Mouse Y") * mouseSensitivity;
                 }
         
         
                     float targetRotationAngle = cameraTarget.eulerAngles.y + rotateTargetOffsetY;
                     float cameraRotationAngle = transform.eulerAngles.y;
         
                     x = Mathf.LerpAngle(cameraRotationAngle, targetRotationAngle, lerpSpeed * Time.deltaTime);
                 }
         
                 y = ClampAngle(y, -50, 50);
         
                 Quaternion rotation = Quaternion.Euler(y, x, 0);
         
                 // Extremely basic collision where the current distance is reduced until the camera is above the ground
                 RaycastHit hit;
                 if (Physics.Raycast(transform.position, -transform.up, out hit, maxCollisionDetectionDistance ))
                 {
                     currentDistance -= collisionCorrectionIncrement;
                 }
         
                 // Smooth zoom
                 currentDistance -= Input.GetAxis("Mouse ScrollWheel") * zoomSensitivity;
                 currentDistance = Mathf.Clamp(currentDistance, zoomMin, zoomMax);
                 distance = Mathf.Lerp(distance, currentDistance, Time.deltaTime * zoomSmooth);
         
                 Vector3 position = cameraTarget.position - (rotation * Vector3.forward * distance + new Vector3(0, -cameraTargetHeight, 0));
         
                 transform.position = position;
                 transform.rotation = rotation;
             }
         
             private float ClampAngle(float angle, float min, float max)
             {
                 if (angle < -360)
                 {
                     angle += 360;
                 }
                 if (angle > 360)
                 {
                     angle -= 360;
                 }
                 return Mathf.Clamp(angle, min, max);
             }
    
    
    
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

6 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Capsule collider going through terrain collider 1 Answer

AddTorque no longer working when collider is added 2 Answers

Change camera rotation point to mesh face 1 Answer

Prevent player from walking through/pushing walls that are Rigidbodies and have Box colliders 1 Answer

Auto-Scrolling Level - crushing player results in death 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges