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 Ampala · Mar 08, 2018 at 11:00 PM · cameraraycastmesheswallwalls

Prevent camera from going through walls and meshes

I would like to prevent the camera from going through walls and meshes. I wrote this code but it dowsn't work properly, because when the camera detects that it has something behind, it stops and do strange stuff if I move the mouse

public class ThirdPersonCamera : MonoBehaviour {

 public bool lockCursor;
 public float mouseSensitivity = 10; //sensibilità
 public Transform target; // il target che la telecamera deve seguire
 public float distanceFromTarget = 2;
 public Vector2 pitchMinMax = new Vector2(-40, 85); //il minimo ed il massimo del pitch

 public float rotationSmoothTime = .12f;
 Vector3 rotationSmoothVelocity;
 Vector3 currentRotation;


 float yaw; //rotazione asse X
 float pitch; //rotazione asse Y

 float distanceFromWall = 0.5f;





 // Use this for initialization
 void Start () 
 {
     if (lockCursor) 
     {
         Cursor.lockState = CursorLockMode.Locked;
         Cursor.visible = false;
     }

 }
 
 // LateUpdate is called dopo tutti gli altri Update methods
 void LateUpdate () 
 {
     //raccolgo input del mouse
     yaw += Input.GetAxis ("Mouse X") * mouseSensitivity;
     pitch -= Input.GetAxis ("Mouse Y") * mouseSensitivity;
     pitch = Mathf.Clamp (pitch, pitchMinMax.x, pitchMinMax.y); //non permette al pitch di superare i due valori

     currentRotation = Vector3.SmoothDamp (currentRotation, new Vector3 (pitch, yaw), ref rotationSmoothVelocity, rotationSmoothTime); //calcola la posizione che deve assumere la telecamera con un po' di smooth

     transform.eulerAngles = currentRotation; //ruota la telecamera

     //hit per i muri telecamera
     RaycastHit hit;
     Vector3 back = transform.TransformDirection(-1 * Vector3.forward);
     Vector3 wantedPosition = Vector3.zero;
     if (Physics.Raycast (target.position, back, out hit, distanceFromTarget) && hit.transform != target)
     {
         wantedPosition = new Vector3 (hit.point.x, hit.point.y, hit.point.z + distanceFromWall);
         //wantedPosition.z = Mathf.Lerp (hit.point.y, pitch, Time.deltaTime * rotationSmoothTime);
         transform.position = Vector3.SmoothDamp(transform.position, wantedPosition, ref rotationSmoothVelocity, rotationSmoothTime, rotationSmoothTime, Time.deltaTime);
     }
     else
         transform.position = target.position - transform.forward * distanceFromTarget; //segue il target mantenendo una certa distanza
     //fine hit muri

     transform.position = target.position - transform.forward * distanceFromTarget; //segue il target mantenendo una certa distanza


 }
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 AiRobotMedia · May 10, 2018 at 07:36 PM

I guess you are doing Sebastion Lagues tutorials as well.

I have just got the same thing working. Note that I am HitTesting from the center of the character and not the players position which would be at floor level.

     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;
 
     public class ThirdPersonCamera : MonoBehaviour
     {
         public bool lockCursor;
         public float mouseSensitivity = 10;
         public Transform target;
         public float dstFromTarget = 3;
 
         public float rotationSmoothTime = .12f;
         Vector3 rotationSmoothVelocity;
         Vector3 currentRotation;
 
         public float minPitch = -40;
         public float maxPitch = 85;
 
         float yaw;
         float pitch;
 
         Vector3 center = new Vector3(0f, 0.5f, 0f);
         RaycastHit hit;
 
         private void Start()
         {
             if (lockCursor)
             {
                 Cursor.lockState = CursorLockMode.Locked;
                 Cursor.visible = false;
             }
         }
 
         void LateUpdate()
         {
             yaw += Input.GetAxis("Mouse X") * mouseSensitivity;
             pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity;
             pitch = Mathf.Clamp(pitch, minPitch, maxPitch);
 
             currentRotation = Vector3.SmoothDamp(currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, rotationSmoothTime);
             transform.eulerAngles = currentRotation;
 
             Vector3 wantedCameraPosition = target.position + center - transform.forward * dstFromTarget;
 
             // Raycasting 
             Vector3 rayDirection = (wantedCameraPosition - (target.position + center)).normalized;
 
             if (Physics.Raycast(target.position + center, rayDirection, out hit, dstFromTarget)
                 && hit.transform != target.parent) // ignore ray-casts that hit the user. DR
             {
                 // Debug.Log(hit.transform.name  + " " + direction.ToString());
                 wantedCameraPosition.x = hit.point.x;
                 wantedCameraPosition.z = hit.point.z;
                 //wantedPosition.y = wantedPosition.y);
             }
 
             transform.position = wantedCameraPosition;
         }
     }
 

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

144 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

Related Questions

Ray Cast not working for camera. 1 Answer

2D Raycast in any direction 1 Answer

Weird mouse look glitch in top down shooter. 0 Answers

Unity raycast not working / returning weird value 0 Answers

Smart camera? 1 Answer


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