Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 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
4
Question by MrRandomFella · Jul 14, 2015 at 05:19 AM · rotationrigidbodyraycasthoveralign

Aligning player to surface

I am currently making an vehicle combat game and I'm struggling to write a script for my vehicles. The player controls a hovering vehicle that sits only a small distance above the ground and rotates on the X and Z axis to match the terrain angles. Almost like it sticks to the surface.

The way I had planned this was to cast a ray down from my rigidbody vehicle to the ground and measure the distance between them. The Y axis height is set to a variable and the ray ensures that the height stays at the variable.

The ray also checks the ground angle and moves the vehicle to match it, but the vehicle cannot climb 90 degree angles.

alt text

I understand what I am trying to do, but I am unsure on how this should be set out in a JavaScript (I haven't worked with raycasting/rigidbodies that often)

hovering.png (28.9 kB)
Comment
Add comment · Show 1
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 MrRandomFella · Jul 14, 2015 at 05:22 AM 0
Share

A similar example would be dodgem arena on the ps1 Link

2 Replies

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

Answer by Cherno · Jul 14, 2015 at 06:28 AM

This should get you started:

 //declare the variables that are needed
 public bool grounded;
 private Vector3 posCur;
 private Quaternion rotCur;
 
 void Update() {
             //declare a new Ray. It will start at this object's position and it's direction will be straight down from the object (in local space, that is)
         Ray ray = new Ray(transform.position, -transform.up);
             //decalre a RaycastHit. This is neccessary so it can get "filled" with information when casting the ray below.
         RaycastHit hit;

             //cast the ray. Note the "out hit" which makes the Raycast "fill" the hit variable with information. The maximum distance the ray will go is 1.5
         if(Physics.Raycast(ray, out hit, 1.5f) == true) {
             //draw a Debug Line so we can see the ray in the scene view. Good to check if it actually does what we want. Make sure that it uses the same values as the actual Raycast. In this case, it starts at the same position, but only goes up to the point that we hit.
             Debug.DrawLine(transform.position, hit.point, Color.green);
                     //store the roation and position as they would be aligned on the surface
             rotCur = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
             posCur = new Vector3(transform.position.x, hit.point.y, transform.position.z);
 
             grounded = true;
 
         }
             //if you raycast didn't hit anything, we are in the air and not grounded.
         else {
             grounded = false;
         }
 
 
         if(grounded == true) {
                     //smoothly rotate and move the objects until it's aligned to the surface. The "5" multiplier controls how fast the changes occur and could be made into a seperate exposed variable
             transform.position = Vector3.Lerp(transform.position, posCur, Time.deltaTime * 5);
             transform.rotation = Quaternion.Lerp(transform.rotation, rotCur, Time.deltaTime * 5);
         }
         else {
                     //if we are not grounded, make the object go straight down in world space (simulating gravity). the "1f" multiplier controls how fast we descend.
             transform.position = Vector3.Lerp(transform.position, transform.position - Vector3.up * 1f, Time.deltaTime * 5);

                     //from memory, I'm not sure why I aded this... Looks like a fail safe to me. When the object is turned too much towards teh front or back, almost instantly (*1000) make it rotate to a better orientation for aligning.
             if(transform.eulerAngles.x > 15) {
                 turnVector.x -= Time.deltaTime * 1000;
             }
             else if(transform.eulerAngles.x < 15) {
                 turnVector.x += Time.deltaTime * 1000;
             }
                     //if we are not grounded, make the vehicle's rotation "even out". Not completey reaslistic, but easy to work with.
             rotCur.eulerAngles = Vector3.zero;
             transform.rotation = Quaternion.Lerp(transform.rotation, rotCur, Time.deltaTime);
 
         }
     }

Comment
Add comment · Show 6 · 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 MrRandomFella · Jul 14, 2015 at 09:55 AM 0
Share

Ok, just converted this to javascript and set turnvector to a Vector3 variable and the script works well, the vehicle matches the angles of the terrain. The only problem I'm having is with the "hovering" part. The vehicle doesn't sit above the ground but rather inside it. How do I fix this?

avatar image Cherno · Jul 14, 2015 at 10:57 AM 0
Share

Try adding to the posCur's y value:

            posCur = new Vector3(transform.position.x, hit.point.y + 1f, transform.position.z);
 
avatar image MrRandomFella · Jul 14, 2015 at 11:27 AM 0
Share

That fixed it, but I have one little issue.

The vehicle tends to align too slowly, often resulting in the whole object clipping out of the track.

Can I just fix that by adjusting a certain variable?

avatar image Cherno · Jul 14, 2015 at 11:44 AM 0
Share

In these lines of code, the multiplier by which time.deltaTime gets multiplied (5) can be changed to your liking. I suggest using a seperate variable for it which you can change from the main body during runtime via the inspector or script.

 transform.position = Vector3.Lerp(transform.position, posCur, Time.deltaTime * 5);
              transform.rotation = Quaternion.Lerp(transform.rotation, rotCur, Time.deltaTime * 5);
avatar image mkShogun96 · Aug 09, 2016 at 11:11 AM 0
Share

HI there @Cherno I just want to thank you for the help!

I am new to game development and had a similar problem and this thread really helped me a lot, not only to solve my problem but to learn new techniques and the coding behind your solution. ($$anonymous$$ight I suggest adding comments next time, since I would have really liked to know what each line of code actually does, but I kinda figured it out and commented it myself).

Again thank you so much for helping out it really helped me a lot!

avatar image Cherno mkShogun96 · Aug 11, 2016 at 01:19 PM 0
Share

Good to hear that it was a big help to you. Yes, after taking another look at my code, I think some comments would have been good. I will try to keep that in $$anonymous$$d for the next time. Thanks for the suggestion.

avatar image
0

Answer by Saddamjit_Singh · Sep 04, 2017 at 07:48 AM

Do this --

 using UnityEngine;
    
        
 
 public class SlopeDetectionScript : MonoBehaviour
       
  {
    
            
 RaycastHit hit;
            
 Quaternion rot;
            
 public  int smooth;
    
            
 
 void Update()
            
 {
                
        Ray ray = new Ray(transform.position, -transform.up);
               
        if (Physics.Raycast(ray, out hit))
               
        {
                    
              rot = Quaternion.FromToRotation(transform.up, hit.normal) * 
              transform.rotation;
                    
              transform.rotation = Quaternion.Lerp(transform.rotation, rot, 
              Time.deltaTime * smooth);
               
        }
            
  }
    
        
  
    
    }
    
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

25 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

Related Questions

Aligning an Object to a Surface, and Rotating it 2 Answers

Need help with limiting rotation. 1 Answer

Rigidbody.AddForce with Raycast? 1 Answer

Input problem 1 Answer

Smoothing orientation to surface normal rotation 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