Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 jasguitar · Jun 30, 2017 at 08:24 PM · cameracollisionraycastterrain

How to get Camera Collision Detection on Terrain

I wrote a third person controller and used part of a collision detection script that I found online. Currently it is able to move the camera in closer whenever objects are inbetween the camera and the player, but not when the terrain in inbetween the camera and the player.

Everything I use for detecting if there is an object between the player and the camera can be found in the OccludeRay method. Here is the code:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class CameraScript : MonoBehaviour {
 
     [SerializeField]private GameObject player;
     [SerializeField]private float cameraRadius;
     [SerializeField]private Vector3 cameraOffset;
     [SerializeField]private LayerMask CamOcclusionLayers;
     private Vector3 camDistance;
     private Vector3 camAnchor;
     private Vector3 camDesiredPosition;
     private Vector3 camMask;
     [HideInInspector]public float cameraAngleX=0;
     [HideInInspector]public float cameraAngleY=0;
 
     // Use this for initialization
     void Start () {
         camAnchor = player.transform.position - cameraOffset;
         transform.position = camAnchor - new Vector3(0,0,cameraRadius);
         
     }
     
     // Update is called once per frame
     void Update () {
         updateCamera ();
     }
 
     void updateCamera()
     {
         cameraAngleX += Input.GetAxis("Mouse X");
         cameraAngleY -= Input.GetAxis("Mouse Y");
 
         if (cameraAngleY > 90) {
             cameraAngleY = 90;
         }
         if (cameraAngleY< -90) {
             cameraAngleY = -90;
         }
         camAnchor = player.transform.position - cameraOffset;
 
         camDistance = new Vector3 (cameraRadius*Mathf.Sin(cameraAngleX*Mathf.PI/180),cameraRadius*Mathf.Sin(cameraAngleY*Mathf.PI/180), cameraRadius*Mathf.Cos(cameraAngleX*Mathf.PI/180));
         camMask = camAnchor - camDistance;
         camDesiredPosition = camAnchor - camDistance;
 
         occludeRay (ref camAnchor);
 
         transform.position = camDesiredPosition;
         transform.LookAt (camAnchor);
 
     }
 
     void occludeRay(ref Vector3 target)
     {
         //declare a new raycast hit.
         RaycastHit wallHit = new RaycastHit();
         //linecast from your player (targetFollow) to your cameras mask (camMask) to find collisions.
         if (Physics.Linecast(target, camMask, out wallHit, CamOcclusionLayers))
         {
             //the smooth is increased so you detect geometry collisions faster.
             //smooth = 10f;
             //the x and z coordinates are pushed away from the wall by hit.normal.
             //the y coordinate stays the same.
             camDesiredPosition = new Vector3(wallHit.point.x + wallHit.normal.x * 0.5f, camDesiredPosition.y, wallHit.point.z + wallHit.normal.z * 0.5f);
         }
     }
 }
 
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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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

I would like to share my solution if anyone is needing. This method minimized passing through terrain very much for me.

What I did is simply, stopping the Camera Zoom by checking the distance of Camera to Terrain by sending a Raycast from Camera to Terrain. If the distance between Camera and Terrain is very short, then the Camera Zoom going below Terrain shouldn't work, but Camera Zoom going above should still work. And if the Camera is higher than Terrain above the minimum limit, then Camera Zoom should work without restriction. Moreover, if Player quickly scrolls to go down to Terrain, there is a little possibility the script couldn't prevent stopping the Player doing this in time, so a Trigger works if Camera collides with the Terrain, thus Camera is returned to a minimum height level smoothly. These are what the below script handles.

Note: The bottom part of the script is your Mouse Scroll code if you are using Mouse Scroll in Zooming, and the rest of the script is to limit the camera going below Terrain. Please make sure to add Sphere Collider (with Trigger on) and Rigidbody (without gravity, freeze rotation X and Z from the constraints too) to camera.

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) //if going up, not down. This part limits going down. 
                     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

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

145 People are following this question.

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

Related Questions

Can someone modify this for me? 0 Answers

Raycast doesn't collide as it should 1 Answer

Weird error with RayCasting (CS1502) 1 Answer

How can I change this script? 0 Answers

Raycast collision on camera see's only part of object 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