Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 Kalbytron · Oct 30, 2013 at 06:19 AM · movementcontroller

Need Help with this movement Script

So far I'm been trying to figure out

1: why it's switching back and forth from grounded to air AFTER jumping and landing.

2: why it's keep on giving me a Null Reference Exception at lines 66 and 110.

3: how to keep the character grounded when walking down slopes

[RequireComponent (typeof (CharacterController))]

public class Movement : MonoBehaviour {

 /// This script moves the character controller forward 
 /// and sideways based on the arrow keys.
 /// It also jumps when pressing space.
 /// Make sure to attach a character controller to the same game object.
 /// It is recommended that you make only one call to Move or SimpleMove per frame.    
 
 
 
 public float speed = 6.0f;
 
 public float jumpHeight = 1.0f;
 public float gravity = 30.0f;
 public float maxFallSpeed = 20f;
     
 public float rotationSpeed = 15.0f;
 public float airSpeed  = 2.0f;
 public bool airControl = true;
 public bool canTurn = true;
 public bool canAirTurn = false;
 public bool canAirJump = false;
 public float maxAirJumps = 0f;    
 
 
 // Checking Movement states
 //bool isMoving = false;
 [SerializeField]
 private bool grounded = false;
 [SerializeField]
 private bool inAir = true;
 [SerializeField]
 private bool jumping = false;
 [SerializeField]
 private bool falling = true;
 private int airJumps = 0;

 // Private vars for stuff
 // Getting direction input
 private float xMove;
 private float zMove;
 
 private CharacterController controller;
 private Animator animator;
 private CollisionFlags collisions;
 private Transform mainCamPos;
 private float savedOffset;
 
 private Vector3 moveDirection = Vector3.zero;

// private Vector3 airVelocity = Vector3.zero; private float verticalSpeed;

 public bool debug = true;
 
 // Use this for initialization
 void Start () {
     controller  = GetComponent<CharacterController>();
     animator    = GetComponent<Animator>();
     mainCamPos  = Camera.main.transform;
     savedOffset = controller.stepOffset;        
     
     if(animator == null)
         return;
 }
 
 // Update is called once per frame
 void Update () {
     
     MovementLogic();
 
 }
 
 void FixedUpdate() {
     
     
     
 }
 
 void MovementLogic() {
 
     //Getting direction input
     xMove = Input.GetAxis("Horizontal");
     zMove = Input.GetAxis("Vertical");
     
    
     // Camera forward
     Vector3 forward = mainCamPos.forward;
     forward.y = 0;
     forward = forward.normalized;
     
     // Camera right
     Vector3 right = new Vector3(forward.z, 0, -forward.x);
         
     // Target direction relative to the camera
     moveDirection = xMove * right + zMove * forward;
     
     // Normalize when going diagnol on keyboard
      if (moveDirection.magnitude > 1.0f)
     {
         moveDirection = moveDirection.normalized;
     }
     
     // When the character is grounded on the floor
     if (controller.isGrounded) {    
         grounded = true;
         inAir = false;
         jumping = false;
         falling = false;
     }
     else {
         grounded = false;
         inAir = true; 
     }
     // When the character is falling in the air
     if (inAir && verticalSpeed < 0f){
         falling = true;
     }
     
     if(animator)
     {
         animator.SetFloat("speed", moveDirection.magnitude);
         animator.SetBool ("jumping", jumping);
         animator.SetBool ("falling", falling);
     }
     
     float pushDown = Mathf.Max (controller.stepOffset, new Vector3(moveDirection.x,0,moveDirection.z).magnitude);
     
     // While the character is grounded
     if (grounded){
         
         moveDirection -= pushDown * Vector3.up;    
         verticalSpeed = moveDirection.y;
         
         controller.stepOffset = savedOffset;
         airJumps = 0;
         
         Jump();
         
         //Moves appropriately with curves and hills

// verticalSpeed = Mathf.Min (verticalSpeed, 0);

     }
     
     // while the character is in air
     if (inAir){
         
         Gravitation();
         
         //To prevent sticking to the ceiling while moving in the air
         controller.stepOffset = 0.0f;
         
         // When your head hits the ceiling, you velocity flips down. Character Controller offset set
         // to zero to prevent sticking to ceiling.
         if((controller.collisionFlags & CollisionFlags.Above) > 0){
             verticalSpeed = -verticalSpeed;
         
         }
         
         //If you can air jump
         if (canAirJump && (airJumps < maxAirJumps)){
             Jump();
             airJumps++;
            }     
     }
     
     if (grounded || canAirTurn){
         // We are grounded, so recalculate
         // move direction directly from axes
         if (canTurn) {
             if(moveDirection != Vector3.zero) {
                 transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation( new Vector3 (moveDirection.x, 0f, moveDirection.z)), Time.deltaTime * rotationSpeed);
             }
         }
     }
     
     
         
     
     // Merge Movement, speed, and gravity;
     Vector3 movement = moveDirection * speed + new Vector3(0, verticalSpeed, 0);
     
     // Move the controller
     controller.Move(movement * Time.deltaTime);
     
     // Debugging Code
     if (debug) {
         Debug.Log (verticalSpeed);
     
     }
 }
 

 void Jump() {
     if (Input.GetButtonDown ("Jump")) {
         
         jumping = true;
         verticalSpeed = CalculateJumpSpeed(jumpHeight);
     }
 }
 
 float CalculateJumpSpeed(float targetJumpHeight)
 {
     return Mathf.Sqrt (2 * targetJumpHeight * gravity);
 }
 
 //This is where the gravity comes from
 void Gravitation()
 {
     // Apply gravity and maximum fall speed
     verticalSpeed -= gravity * Time.deltaTime;
 }
 
 void SetVelocity(Vector3 newMovement)
 {
     moveDirection = newMovement;
 }

}

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

0 Replies

· Add your reply
  • Sort: 

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

15 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

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

How do I set up my players controller script (How do I change the controls used to move and look) 2 Answers

Movement Conflict 1 Answer

CharacterController unexpectedly moving up 0 Answers

What's the best alternative to Character Controller? 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