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 GiggleSquid · Mar 29, 2015 at 08:26 AM · c#scripting problemjumpjumping

Jumping in only the direction of the last key pressed

Hai guys. I've been trying to figure this out for about 5 hours now, I have a first person controller script based on the Unity Standard Assets one and I'm trying to figure out how to jump to the direction of the key pressed and not be able to move in any other direction until the character is grounded again. Does anyone have any idea on how to do this?

This is my Player script

 using UnityEngine;
 using System.Collections;
 using Random = UnityEngine.Random;
 
 [RequireComponent(typeof (CharacterController))]
 [RequireComponent(typeof (AudioSource))]
 public class Player : MonoBehaviour {
 
     public bool isWalking;
     public float walkSpeed;
     public float runSpeed;
     [Range(0f, 1f)] public float runstepLenghten;
     public float jumpSpeed;
     public float stickToGroundForce;
     public float gravityMultiplier;
     public MouseLook mouseLook;
     public bool useFovKick;
     public FOVKick fovKick = new FOVKick();
     public bool useHeadBob;
     public CurveControlledBob headBob = new CurveControlledBob();
     public LerpControlledBob jumpBob = new LerpControlledBob();
     public float stepInterval;
     public AudioClip[] footstepSounds;
     public AudioClip jumpSound;
     public AudioClip landSound;
 
     private Camera camera = new Camera();
     private bool jump;
     private float yRotation;
     private Vector2 input;
     private Vector3 moveDir = Vector3.zero;
     private CharacterController characterController;
     private CollisionFlags collisionFlags;
     private bool previouslyGrounded;
     private Vector3 originalCameraPosition;
     private float stepCycle;
     private float nextStep;
     private bool jumping;
     private AudioSource audioSource;
 
     private void Start(){
         characterController = GetComponent<CharacterController>();
         camera = Camera.main;
         originalCameraPosition = camera.transform.localPosition;
         fovKick.Setup(camera);
         headBob.Setup(camera, stepInterval);
         stepCycle = 0f;
         nextStep = stepCycle / 2f;
         jumping = false;
         audioSource = GetComponent<AudioSource>();
         mouseLook.Init(transform , camera.transform);
     }
 
     private void Update(){
         RotateView();
         // the jump state needs to read here to make sure it is not missed
         if (!jump)
         {
             jump = Input.GetButtonDown("Jump");
         }
         
         if (!previouslyGrounded && characterController.isGrounded)
         {
             StartCoroutine(jumpBob.DoBobCycle());
             PlayLandingSound();
             moveDir.y = 0f;
             jumping = false;
         }
         if (!characterController.isGrounded && !jumping && previouslyGrounded)
         {
             moveDir.y = 0f;
         }
         
         previouslyGrounded = characterController.isGrounded;
     }
     
     private void PlayLandingSound(){
         audioSource.clip = landSound;
         audioSource.Play();
         nextStep = stepCycle + .5f;
     }
     
     private void FixedUpdate(){
         float speed;
         GetInput(out speed);
         // always move along the camera forward as it is the direction that it being aimed at
         Vector3 desiredMove = transform.forward * input.y + transform.right * input.x;
         
         // get a normal for the surface that is being touched to move along it
         RaycastHit hitInfo;
         Physics.SphereCast(transform.position, characterController.radius, Vector3.down, out hitInfo, characterController.height / 2f);
         desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
         
         moveDir.x = desiredMove.x * speed;
         moveDir.z = desiredMove.z * speed;
         
         
         if (characterController.isGrounded)
         {
             moveDir.y = -stickToGroundForce;
             
             if (jump)
             {
                 moveDir.y = jumpSpeed;
                 PlayJumpSound();
                 jump = false;
                 jumping = true;
             }
         }
         else
         {
             moveDir += Physics.gravity * gravityMultiplier * Time.fixedDeltaTime;
         }
 
         if (!characterController.isGrounded) {            
         }
         collisionFlags = characterController.Move(moveDir * Time.fixedDeltaTime);
         
         ProgressStepCycle(speed);
         UpdateCameraPosition(speed);
     }
 
     private void PlayJumpSound(){
         audioSource.clip = jumpSound;
         audioSource.Play();
     }
 
     private void ProgressStepCycle(float speed){
         if (characterController.velocity.sqrMagnitude > 0 && (input.x != 0 || input.y != 0))
         {
             stepCycle += (characterController.velocity.magnitude + (speed *(isWalking ? 1f : runstepLenghten)))*
                 Time.fixedDeltaTime;
         }
         
         if (!(stepCycle > nextStep))
         {
             return;
         }
         
         nextStep = stepCycle + stepInterval;
         
         PlayFootStepAudio();
     }
     
     private void PlayFootStepAudio(){
         if (!characterController.isGrounded)
         {
             return;
         }
         // pick & play a random footstep sound from the array,
         // excluding sound at index 0
         int n = Random.Range(1, footstepSounds.Length);
         audioSource.clip = footstepSounds[n];
         audioSource.PlayOneShot(audioSource.clip);
         // move picked sound to index 0 so it's not picked next time
         footstepSounds[n] = footstepSounds[0];
         footstepSounds[0] = audioSource.clip;
     }
 
     private void UpdateCameraPosition(float speed){
         Vector3 newCameraPosition;
         if (!useHeadBob)
         {
             return;
         }
         if (characterController.velocity.magnitude > 0 && characterController.isGrounded)
         {
             camera.transform.localPosition = headBob.DoHeadBob(characterController.velocity.magnitude + (speed * (isWalking ? 1f : runstepLenghten)));
             newCameraPosition = camera.transform.localPosition;
             newCameraPosition.y = camera.transform.localPosition.y - jumpBob.Offset();
         }
         else
         {
             newCameraPosition = camera.transform.localPosition;
             newCameraPosition.y = originalCameraPosition.y - jumpBob.Offset();
         }
         camera.transform.localPosition = newCameraPosition;
     }
 
     private void GetInput(out float speed){
         // Read input
         float horizontal = Input.GetAxis("Horizontal");
         float vertical = Input.GetAxis("Vertical");
         
         bool waswalking = isWalking;
 
         isWalking = !Input.GetKey(KeyCode.LeftShift);
 
         // set the desired speed to be walking or running
         speed = isWalking ? walkSpeed : runSpeed;
         input = new Vector2(horizontal, vertical);
         
         // normalize input if it exceeds 1 in combined length:
         if (input.sqrMagnitude > 1)
         {
             input.Normalize();
         }
         
         // handle speed change to give an fov kick
         // only if the player is going to a run, is running and the fovkick is to be used
         if (isWalking != waswalking && useFovKick && characterController.velocity.sqrMagnitude > 0)
         {
             StopAllCoroutines();
             StartCoroutine(!isWalking ? fovKick.FOVKickUp() : fovKick.FOVKickDown());
         }
     }
 
     private void RotateView(){
         mouseLook.LookRotation (transform, camera.transform);
     }
     
     
     private void OnControllerColliderHit(ControllerColliderHit hit){
         Rigidbody body = hit.collider.attachedRigidbody;
         //dont move the rigidbody if the character is on top of it
         if (collisionFlags == CollisionFlags.Below)
         {
             return;
         }
         
         if (body == null || body.isKinematic)
         {
             return;
         }
         body.AddForceAtPosition(characterController.velocity * 0.1f, hit.point, ForceMode.Impulse);
     }
 }
 

Sorry for the extremely long script. And please tell me if I wasn't clear enough with my question.

Comment
Add comment · Show 4
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 AlwaysSunny · Mar 28, 2015 at 06:03 PM 1
Share

Based on your request as worded, couldn't you just disallow all input while not grounded?

The whole "steering in the air" concept is fairly common in FPS games, but it's altogether unrealistic unless the character is part flying-squirrel. Only allowing input in the launch direction is almost fruitless unless you've got a very specific need. Like a jet pack or something? In which case, you could use that "jetpack-jump" button to control the duration of the boost, without caring about x,y input (use the last grounded input to establish the non-changing direction).

If you really want exactly what you're asking for, keep a record of the last frame's input, and when you're not grounded, only respond to input in that direction until you're grounded again.

You can compare vectors in a useful way here by responding to input according to its Dot Product versus your recorded "last grounded input".

avatar image GiggleSquid · Mar 28, 2015 at 06:10 PM 0
Share

How would I go about recording the last frame's input? Sorry, a bit of a novice over here :p

avatar image AlwaysSunny · Mar 28, 2015 at 06:16 PM 1
Share

Easy! $$anonymous$$eep a class-scope vector lastInput.

 Vector2 lastInput;
 
 void Update() {
   Vector2 currentInput = new Vector2( Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));

   // make use of the currentInput, including any logic which
   // makes comparisons between last & current input

   // at the end of Update, write
   lastInput = currentInput;
 }
avatar image GiggleSquid · Mar 28, 2015 at 08:22 PM 0
Share

Right, I seemed to have gone in a massive circle. One of my original problems was the character stopping dead then jumping rather than jumping into the direction that the player last moved in, do you have any idea? P.S I can show you the code if you'd like?

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Character not jumping high enough 1 Answer

Super Ghouls 'n Ghosts style jumps & double jumps? 1 Answer

Jumping mechanism 1 Answer

Jump higher when holding button 5 Answers

Confused as to why he only jumps while walking? 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