• 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
3
Question by Ricardo Arango · Dec 05, 2009 at 02:55 AM · physicsrigidbodycharacter

Make rigidbody walk like character controller

I am using a rigidbody to model my character. I have to use it because I need full physics. But the problem is that it accelerates/decelerates when moving. Is there a way to avoid this, so it has constant velocity?

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

6 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by ugufyman · Oct 10, 2017 at 12:41 AM

The code you wrote is fantastic and works perfectly but sadly it was a little outdated, not too bad just some changes between unity 4 and 5 did some damage so i tried to fix that and reupload it

p.s (I added camera control to it, you just have to set the sensitivity and the camera gameobject, hopefully not too bad)

'using UnityEngine; using System.Collections;

[RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(CapsuleCollider))]

public class Movement : MonoBehaviour { #region Variables (private)

 private bool grounded = false;
 private Vector3 groundVelocity;
 private CapsuleCollider capsule;

 // Inputs Cache
 private bool jumpFlag = false;

 #endregion

 #region Properties (public)

 // Speeds
 public float walkSpeed = 8.0f;
 public float walkBackwardSpeed = 4.0f;
 public float runSpeed = 14.0f;
 public float runBackwardSpeed = 6.0f;
 public float sidestepSpeed = 8.0f;
 public float runSidestepSpeed = 12.0f;
 public float maxVelocityChange = 10.0f;

 // Air
 public float inAirControl = 0.1f;
 public float jumpHeight = 2.0f;

 // Can Flags
 public bool canRunSidestep = true;
 public bool canJump = true;
 public bool canRun = true;

 Transform cam;
 public GameObject eyes;
 float rotX;
 float rotY;
 public float sensitivity;
 #endregion

 #region Unity event functions

 /// <summary>
 /// Use for initialization
 /// </summary>
 void Awake()
 {
     capsule = GetComponent<CapsuleCollider>();
     this.GetComponent<Rigidbody>().freezeRotation = true;
     this.GetComponent<Rigidbody>().useGravity = true;
 }

 /// <summary>
 /// Use this for initialization
 /// </summary>
 void Start()
 {

 }

 /// <summary>
 /// Update is called once per frame
 /// </summary>
 void Update()
 {
     // Cache the input
     if (Input.GetButtonDown("Jump"))
         jumpFlag = true;

     //Mouse Input & fps camera movement
     cam = GetComponentInChildren<Camera> ().transform;
     Vector3 myPos = GetComponent<Transform> ().position;
     cam.GetComponent<Transform> ().position = new Vector3 (myPos.x, myPos.y, myPos.z);

     rotX = Input.GetAxis ("Mouse X");
     rotY = Input.GetAxis ("Mouse Y");

     this.GetComponent<Transform> ().Rotate (0, rotX * sensitivity, 0);
     eyes.GetComponent<Transform> ().Rotate (-rotY * sensitivity, 0, 0);
 }

 /// <summary>
 /// Update for physics
 /// </summary>
 void FixedUpdate()
 {


     // Cache de input
     var inputVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

     // On the ground
     if (grounded)
     {
         // Apply a force that attempts to reach our target velocity
         var velocityChange = CalculateVelocityChange(inputVector);
         this.GetComponent<Rigidbody>().AddForce(velocityChange, ForceMode.VelocityChange);

         // Jump
         if (canJump && jumpFlag)
         {
             Rigidbody rig = this.GetComponent<Rigidbody> ();
             jumpFlag = false;
             this.GetComponent<Rigidbody>().velocity = new Vector3(rig.velocity.x, rig.velocity.y + CalculateJumpVerticalSpeed(), rig.velocity.z);
         }

         // By setting the grounded to false in every FixedUpdate we avoid
         // checking if the character is not grounded on OnCollisionExit()
         grounded = false;
     }
     // In mid-air
     else
     {
         // Uses the input vector to affect the mid air direction
         var velocityChange = transform.TransformDirection(inputVector) * inAirControl;
         this.GetComponent<Rigidbody>().AddForce(velocityChange, ForceMode.VelocityChange);
     }
 }

 // Unparent if we are no longer standing on our parent
 void OnCollisionExit(Collision collision)
 {
     if (collision.transform == transform.parent)
         transform.parent = null;
 }

 // If there are collisions check if the character is grounded
 void OnCollisionStay(Collision col)
 {
     TrackGrounded(col);
 }

 void OnCollisionEnter(Collision col)
 {
     TrackGrounded(col);
 }

 #endregion

 #region Methods

 // From the user input calculate using the set up speeds the velocity change
 private Vector3 CalculateVelocityChange(Vector3 inputVector)
 {
     // Calculate how fast we should be moving
     var relativeVelocity = transform.TransformDirection(inputVector);
     if (inputVector.z > 0)
     {
         relativeVelocity.z *= (canRun && Input.GetButton("Sprint")) ? runSpeed : walkSpeed;
     }
     else
     {
         relativeVelocity.z *= (canRun && Input.GetButton("Sprint")) ? runBackwardSpeed : walkBackwardSpeed;
     }
     relativeVelocity.x *= (canRunSidestep && Input.GetButton("Sprint")) ? runSidestepSpeed : sidestepSpeed;

     // Calcualte the delta velocity
     var currRelativeVelocity = this.GetComponent<Rigidbody>().velocity - groundVelocity;
     var velocityChange = relativeVelocity - currRelativeVelocity;
     velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
     velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
     velocityChange.y = 0;

     return velocityChange;
 }

 // From the jump height and gravity we deduce the upwards speed for the character to reach at the apex.
 private float CalculateJumpVerticalSpeed()
 {
     return Mathf.Sqrt(2f * jumpHeight * Mathf.Abs(Physics.gravity.y));
 }

 // Check if the base of the capsule is colliding to track if it's grounded
 private void TrackGrounded(Collision collision)
 {
     var maxHeight = capsule.bounds.min.y + capsule.radius * .9f;
     foreach (var contact in collision.contacts)
     {
         if (contact.point.y < maxHeight)
         {
             if (isKinematic(collision))
             {
                 // Get the ground velocity and we parent to it
                 groundVelocity = collision.rigidbody.velocity;
                 transform.parent = collision.transform;
             }
             else if (isStatic(collision))
             {
                 // Just parent to it since it's static
                 transform.parent = collision.transform;
             }
             else
             {
                 // We are standing over a dinamic object,
                 // set the groundVelocity to Zero to avoid jiggers and extreme accelerations
                 groundVelocity = Vector3.zero;
             }

             // Esta en el suelo
             grounded = true;
         }

         break;
     }
 }

 private bool isKinematic(Collision collision)
 {
     return isKinematic(GetComponent<Collider>().transform);
 }

 private bool isKinematic(Transform transform)
 {
     return transform.GetComponent<Rigidbody>() && transform.GetComponent<Rigidbody>().isKinematic;
 }

 private bool isStatic(Collision collision)
 {
     return isStatic(collision.transform);
 }

 private bool isStatic(Transform transform)
 {
     return transform.gameObject.isStatic;
 }

 #endregion

}

` code kinda got screwed up a bit, just make sure to grab the top bit as well, sorry im new to this

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
  • ‹
  • 1
  • 2

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

How do I make a rigidbody move on command (ie A Player Character)? 1 Answer

Character Controller Jittering 0 Answers

How to prevent friction for character along vertical surfaces? 2 Answers

Character Controller children of a car: Inertia effect, delay effect, what??? 1 Answer

My character is controlled with Rigidbody, How do I make my character NOT run through objects? 2 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